diff --git a/.github/workflows/effect-service-shaking.yml b/.github/workflows/effect-service-shaking.yml new file mode 100644 index 000000000000..7b3521b95b47 --- /dev/null +++ b/.github/workflows/effect-service-shaking.yml @@ -0,0 +1,110 @@ +name: Effect Service Shaking + +# Fork-owned CI for `experimental.effectServiceShaking`, scoped to Effect's +# use case on Node: one Linux job that runs the Effect service fixtures and the +# real-Effect gates through the JS API. It builds only the integration test +# binary, the NAPI binding and the JS glue those checks need. The rest of +# Rolldown's CI (full integration suite, test262, other targets, lints) is +# intentionally not run here. + +on: + # PR runs only, so a push to the PR branch does not start a second run. + pull_request: + branches: + - effect-pinned-v1.2.16 + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + CARGO_TERM_COLOR: always + CARGO_INCREMENTAL: 0 + +jobs: + effect-service-shaking: + name: Effect service fixtures and real-Effect gates (Linux, Node 24) + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - uses: pnpm/action-setup@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 24 + cache: pnpm + + # Fixtures resolve npm packages from the root, including `effect` for the + # real-Effect gates. + - run: pnpm install --frozen-lockfile --ignore-scripts + + - name: Install the pinned Rust toolchain + run: rustup show + + - uses: Swatinem/rust-cache@v2 + with: + key: effect-service-shaking + + # Compile once with the optimized `effect-verify` profile, then run the + # fixtures against the prebuilt binary under a hard 10 second budget. A + # timeout fails the job (exit 124); it is never treated as a pass. + - name: Build the Effect service fixture runner + run: cargo test --profile effect-verify -p rolldown --test integration --no-run + + - name: Effect service fixtures (stub and real Effect, 10s budget) + run: timeout 10 cargo test --profile effect-verify -p rolldown --test integration -- effect_service + + - name: Effect service snapshots are up to date + run: | + changes=$(git status --porcelain -- crates/rolldown/tests/rolldown/tree_shaking/effect_service crates/rolldown/tests/rolldown/tree_shaking/effect_service_real) + if [ -n "$changes" ]; then + echo "$changes" + git diff -- crates/rolldown/tests/rolldown/tree_shaking + exit 1 + fi + + # Only the binding and the JS glue; the JS type check is not needed to + # run the gates. + - name: Build the NAPI binding (debug) + run: pnpm --filter rolldown build-binding + + - name: Build the JS glue + run: pnpm --filter rolldown build-node + + # Bundles the two real-Effect removal gates through the JS API with the + # option on, then runs each gate's own `_test.mjs` (behaviour and removal + # checks). Other `effect_service_real` fixtures are covered by the cargo + # step above. + - name: Real-Effect gates through the JS API + run: | + cat > run-gates.mjs <<'SCRIPT' + import { rolldown } from './packages/rolldown/dist/index.mjs' + import { execFileSync } from 'node:child_process' + import fs from 'node:fs' + import path from 'node:path' + + const root = 'crates/rolldown/tests/rolldown/tree_shaking/effect_service_real' + for (const name of ['lifecycle', 'cross_module']) { + const dir = path.resolve(root, name) + const bundle = await rolldown({ + input: path.join(dir, 'main.js'), + cwd: dir, + platform: 'node', + experimental: { effectServiceShaking: true }, + }) + await bundle.write({ dir: path.join(dir, 'dist'), format: 'esm' }) + await bundle.close() + fs.writeFileSync(path.join(dir, 'dist', 'package.json'), '{ "type": "module" }') + execFileSync(process.execPath, ['_test.mjs'], { cwd: dir, stdio: 'inherit' }) + console.log(`${name}: ok`) + } + SCRIPT + node run-gates.mjs \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 6c4758f9b921..c6963c50df8a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -339,3 +339,12 @@ opt-level = "s" # it will strip these information for non-debug files debug = "full" strip = "none" + +# Effect service shaking verification: the fixtures bundle the real `effect` +# package four times each, which is parse-bound in an unoptimized build. +[profile.effect-verify] +inherits = "test" +opt-level = 1 + +[profile.effect-verify.package."*"] +opt-level = 3 diff --git a/crates/rolldown/examples/effect_service_shaking.rs b/crates/rolldown/examples/effect_service_shaking.rs new file mode 100644 index 000000000000..4e1d56b7c12a --- /dev/null +++ b/crates/rolldown/examples/effect_service_shaking.rs @@ -0,0 +1,56 @@ +#![expect(clippy::print_stdout, reason = "prints measurements")] + +use std::time::Instant; + +use rolldown::{Bundler, BundlerOptions, ExperimentalOptions, InputItem, OutputFormat, Platform}; +use sugar_path::SugarPath; + +// Bundles one entry twice, without and with `experimental.effectServiceShaking`, +// and reports the output size and the median build time of each. +// +// cargo run --release --example effect_service_shaking -- [runs] + +async fn build(entry: &std::path::Path, out_dir: &std::path::Path, enabled: bool) -> u128 { + let mut bundler = Bundler::new(BundlerOptions { + input: Some(vec![InputItem { + name: Some("main".to_string()), + import: entry.to_string_lossy().into_owned(), + }]), + cwd: Some(entry.parent().unwrap().to_path_buf()), + dir: Some(out_dir.to_string_lossy().into_owned()), + format: Some(OutputFormat::Esm), + platform: Some(Platform::Node), + experimental: Some(ExperimentalOptions { + effect_service_shaking: Some(enabled), + ..Default::default() + }), + ..Default::default() + }) + .expect("Failed to create bundler"); + let start = Instant::now(); + bundler.write().await.expect("build failed"); + start.elapsed().as_micros() +} + +#[tokio::main] +async fn main() { + let args: Vec = std::env::args().collect(); + let entry = std::path::Path::new(&args[1]).absolutize().into_owned(); + let out = std::path::Path::new(&args[2]).absolutize().into_owned(); + let runs: usize = args.get(3).and_then(|n| n.parse().ok()).unwrap_or(5); + // Interleave the two configurations so machine load affects both alike. + let mut times = [vec![], vec![]]; + for _ in 0..runs { + for (index, enabled) in [false, true].into_iter().enumerate() { + let dir = out.join(if enabled { "on" } else { "off" }); + times[index].push(build(&entry, &dir, enabled).await); + } + } + for (index, label) in ["off", "on"].into_iter().enumerate() { + let times = &mut times[index]; + times.sort_unstable(); + let size = + std::fs::metadata(out.join(label).join("main.js")).map(|m| m.len()).unwrap_or_default(); + println!("{label}: {size} bytes, median {} ms", times[times.len() / 2] / 1000); + } +} diff --git a/crates/rolldown/src/stages/link_stage/effect_service_shaking.rs b/crates/rolldown/src/stages/link_stage/effect_service_shaking.rs new file mode 100644 index 000000000000..b5cebff8c77b --- /dev/null +++ b/crates/rolldown/src/stages/link_stage/effect_service_shaking.rs @@ -0,0 +1,2896 @@ +//! Experimental removal of Effect service methods that no consumer reads. +//! +//! Enabled with `experimental.effectServiceShaking`. The pass runs in the link +//! stage, after symbols are bound and before statements are included, and +//! works on the module ASTs with oxc's scoping and Rolldown's symbol database. +//! +//! Base case only: +//! - Service keys are module-level `const K = Context.Service(...)` declarations +//! with a literal key string, or `class K extends Context.Service<..>()("key")` +//! whose body never mentions `this`. +//! - Consumers are `const s = yield* K` (or `const { a } = yield* K`) inside an +//! `Effect.gen` / `Effect.fn` generator, where `s` is only read with static +//! member access. +//! - Providers are `Layer.succeed(K, {...})` and `Layer.effect(K, e)` where `e` is +//! built from `Effect.gen`, `Effect.sync`, `Effect.succeed` and +//! `Effect.acquireRelease`, and returns `K.of({...})` or `{...}`. Outside the +//! trusted packages, `e` may also be `make(args)` for a module-level +//! `Effect.fn` constructor returning the object built by a module-level +//! function, when every reference to both is such a followed call. +//! +//! Demand is attached to the key string. Reads inside a removed method, or +//! inside a constructor-local function only that method used, do not count: +//! demand is a least fixpoint over code that can still run. Code that runs +//! while a provider is constructed always counts, and the pass never removes +//! statements other than unused local `const` functions, so acquisition, +//! release and construction-time calls keep running. +//! +//! Anything outside the base case keeps every method of the key involved. +//! +//! The pass relies on the POC contract (`docs/in-depth/effect-service-shaking.md`): +//! user code reaches services only through keyed lookups and does not reflect +//! on Effect runtime objects (A1), the program is closed (A2), Effect reads +//! services only by key (A3), and there is one bundled `effect` (A4). The +//! cheap syntactic breaches (code loading, entry exports, external imports, +//! string-keyed Context APIs, keyed lookups other than `yield*` by an untracked +//! key, builtin prototype writes) turn the pass off. + +use oxc::{ + allocator::Vec as ArenaVec, + ast::{ + AstKind, + ast::{ + Argument, AssignmentTargetPropertyIdentifier, AssignmentTargetPropertyProperty, + BinaryOperator, BindingPattern, BindingProperty, CallExpression, Class, ClassElement, + ComputedMemberExpression, Declaration, Expression, Function, FunctionBody, FunctionType, + IdentifierReference, ImportExpression, ObjectExpression, ObjectPropertyKind, Program, + PropertyKey, PropertyKind, Statement, StaticMemberExpression, UnaryOperator, + VariableDeclarationKind, VariableDeclarator, YieldExpression, + }, + }, + ast_visit::{VisitJs, VisitJsMut, walk_js, walk_js_mut}, + semantic::{ReferenceId, Scoping, SymbolFlags, SymbolId}, + span::{GetSpan, Span}, +}; +use rolldown_common::{ + GetLocalDb, Module, ModuleIdx, Specifier, StmtInfoIdx, SymbolOrMemberExprRef, SymbolRef, + SymbolRefDb, +}; +use rolldown_error::BuildDiagnostic; +use rustc_hash::{FxHashMap, FxHashSet}; + +use super::LinkStage; + +// Under the POC contract (A1) user code reaches services only through keyed +// lookups. These cheap syntactic cases turn the pass off instead of relying on it. +// +// Context functions that read or build a service map by key string. +const CONTEXT_INTERNAL_APIS: &[&str] = &["Context.getOrUndefinedUnsafe", "Context.makeUnsafe"]; +// Keyed lookups other than `yield*`: their key argument may be a key the pass +// does not track, such as `{ key: "app/Store" }`. +const KEYED_LOOKUPS: &[&str] = &[ + "Context.get", + "Context.getUnsafe", + "Context.getOption", + "Context.getOrElse", + "Context.getOrUndefined", + "Context.pick", + "Context.omit", + "Effect.service", + "Effect.serviceOption", + "Effect.updateService", + "Effect.updateServiceScoped", + "Layer.updateService", + "Stream.updateService", + "Channel.updateService", +]; +// Data-last pipeables of `Effect.fn` constructors that only change the context +// or tracing of the constructor, never handing its result to user code. +const CONTEXT_PIPEABLES: &[&str] = + &["Effect.updateService", "Effect.provideService", "Effect.withSpan", "Effect.annotateLogs"]; +// Layer combinators that may be applied with `.pipe(...)`, curried. +const PIPED_LAYER_COMBINATORS: &[&str] = &["Layer.provide", "Layer.provideMerge", "Layer.merge"]; + +/// Arguments of a keyed lookup or `provideService` call that are keys, by API +/// and argument count; `None` when the shape is not recognised. +fn key_arguments(api: &str, argc: usize) -> Option> { + let index = match (api, argc) { + ("Context.pick" | "Context.omit", _) => return Some((0..argc).collect()), + ("Context.get" | "Context.getUnsafe" | "Context.getOption" | "Context.getOrUndefined", 2) + | ( + "Context.getOrElse" + | "Effect.updateService" + | "Layer.updateService" + | "Stream.updateService" + | "Channel.updateService" + | "Effect.provideService" + | "Effect.provideServiceEffect", + 3, + ) => 1, + ("Context.get" | "Context.getUnsafe" | "Context.getOption" | "Context.getOrUndefined", 1) + | ( + "Context.getOrElse" + | "Effect.updateService" + | "Layer.updateService" + | "Stream.updateService" + | "Channel.updateService" + | "Effect.provideServiceEffect", + 2, + ) + | ("Effect.provideService", 1 | 2) + | ("Effect.updateServiceScoped" | "Effect.service" | "Effect.serviceOption", 1..) => 0, + _ => return None, + }; + Some(vec![index]) +} + +// Ways to run code that is not part of the module graph (A2), by global name, +// member name (`globalThis.eval`, `fn.constructor`, `process.getBuiltinModule`) +// or imported name. +const CODE_LOADERS: &[&str] = &[ + "eval", + "Function", + "require", + "constructor", + "createRequire", + "getBuiltinModule", + "compileFunction", + "runInThisContext", + "runInNewContext", + "runInContext", +]; +// Node modules whose operations run code in this realm (A2). +const CODE_LOADING_MODULES: &[&str] = &["vm", "module", "inspector", "repl"]; +// Host values that lead to code loaders (`process.getBuiltinModule`, the global +// `eval`): usable only through constant member names, calls and `typeof`. +// Names of the global object; `globalThis.Reflect` is the global `Reflect`. +const GLOBAL_OBJECTS: &[&str] = &["globalThis", "global", "self", "window"]; +const CAPABILITY_GLOBALS: &[&str] = + &["process", "globalThis", "global", "self", "window", "module"]; +// Members a class-form key inherits from `Context.Service` (effect 4.1.2), and +// function members; a class key may not redeclare them. Names starting with +// `~` (`~effect/Effect`) are protocol ids too. +const SERVICE_PROTOCOL: &[&str] = &[ + "of", + "key", + "use", + "useSync", + "context", + "pipe", + "toJSON", + "toString", + "name", + "length", + "prototype", + "caller", + "arguments", +]; +// Reading one of these on a service observes the whole object. +const INHERITED_MEMBERS: &[&str] = &[ + "constructor", + "hasOwnProperty", + "isPrototypeOf", + "propertyIsEnumerable", + "toLocaleString", + "toString", + "valueOf", + "__proto__", + "__defineGetter__", + "__defineSetter__", + "__lookupGetter__", + "__lookupSetter__", +]; +// Node builtins. Importing one observes nothing; using a code-loading one +// (`CODE_LOADING_MODULES`) turns the pass off. +const NODE_BUILTINS: &[&str] = &[ + "assert", + "assert/strict", + "async_hooks", + "buffer", + "child_process", + "cluster", + "console", + "constants", + "crypto", + "dgram", + "diagnostics_channel", + "dns", + "dns/promises", + "domain", + "events", + "fs", + "fs/promises", + "http", + "http2", + "https", + "inspector", + "module", + "net", + "os", + "path", + "path/posix", + "path/win32", + "perf_hooks", + "process", + "punycode", + "querystring", + "readline", + "readline/promises", + "repl", + "stream", + "stream/promises", + "stream/web", + "string_decoder", + "timers", + "timers/promises", + "tls", + "trace_events", + "tty", + "url", + "util", + "util/types", + "v8", + "vm", + "wasi", + "worker_threads", + "zlib", +]; + +/// How a trusted module's exports are named: `Effect.map` for the effect +/// package, `@effect/platform-node/NodeRuntime.runMain` otherwise. +fn trusted_prefix(id: &str) -> Option { + let id = id.replace('\\', "/"); + let markers: &[(&str, &str)] = &[ + ("/node_modules/effect/", "effect"), + ("/packages/effect/", "effect"), + ("/node_modules/@effect/platform-node/", "@effect/platform-node"), + ("/packages/platform/node/", "@effect/platform-node"), + ("/node_modules/@effect/platform-node-shared/", "@effect/platform-node-shared"), + ("/packages/platform/node-shared/", "@effect/platform-node-shared"), + ]; + for (marker, package) in markers { + let Some(index) = id.rfind(marker) else { continue }; + let mut rest = &id[index + marker.len()..]; + for prefix in ["src/", "dist/esm/", "dist/"] { + if let Some(stripped) = rest.strip_prefix(prefix) { + rest = stripped; + break; + } + } + let rest = rest.rsplit_once('.').map_or(rest, |(stem, _)| stem); + return Some(if *package == "effect" { rest.to_string() } else { format!("{package}/{rest}") }); + } + None +} + +fn strip<'b, 'a>(expr: &'b Expression<'a>) -> &'b Expression<'a> { + let mut expr = expr; + loop { + expr = match expr { + Expression::ParenthesizedExpression(e) => &e.expression, + Expression::TSAsExpression(e) => &e.expression, + Expression::TSSatisfiesExpression(e) => &e.expression, + Expression::TSNonNullExpression(e) => &e.expression, + Expression::TSTypeAssertion(e) => &e.expression, + _ => return expr, + } + } +} + +enum KeyCreation { + Literal(String), + Dynamic, +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +enum Resolved { + Symbol(SymbolRef), + Namespace(ModuleIdx), +} + +/// Where a chain of namespace members starting at an identifier ends. +enum NamespaceChain { + /// At an exported binding; `span` is the whole member chain, which is the + /// expression at ancestor `depth`. + Export { symbol: SymbolRef, span: Span, depth: usize }, + /// A namespace object used as a value. + Value(Span), + /// A member that is not exported. + Unresolved, +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +enum Guard { + /// A property of a provider object literal: (site, property index). + Property(usize, usize), + /// A constructor-local `const` function. + Binding(SymbolRef), +} + +/// Where a Layer or Context built from a provider ends up. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Container { + /// Consumed by `Effect.provide` or `Layer.launch`. + Terminal, + /// Stored in a `const`, whose uses are checked in turn. + Binding(SymbolRef), + /// Returned from a module-level function, whose calls are checked in turn. + Factory(SymbolRef), + Escape, +} + +#[derive(Debug)] +struct RefInfo { + module: ModuleIdx, + span: Span, + top_stmt: usize, + chain: Vec, + /// Static member read on the reference: (name, is a write target). + member: Option<(String, bool)>, + container: Container, + /// Where the result flows when the reference is called directly. + call_result: Option, + /// The root-scope symbol referenced, for statement bookkeeping. + root_symbol: Option, +} + +#[derive(Debug)] +struct Prop { + name: Option, + span: Span, + prunable: bool, + /// May read other properties through `this` when called as a method, so + /// keeping it keeps every property. + this_risk: bool, +} + +#[derive(Debug)] +struct Site { + module: ModuleIdx, + keys: FxHashSet, + props: Vec, + /// Keep every property, e.g. a method may read `this`. + top: bool, + /// Locals bound to the provider object before it reaches a Context, such as + /// an `acquireRelease` release callback parameter. + bindings: Vec, + /// Constructor and builder functions the object is returned through. Every + /// reference to them must be a call the pass followed into a provider. + via: Vec, +} + +/// A provider object literal found in an Effect expression. +struct FoundSite { + module: ModuleIdx, + /// Span start of the literal. + start: u32, + /// Locals bound to the object before it reaches a Context. + bindings: Vec, + /// Keep every property. + top: bool, + /// Constructor and builder functions the object is returned through. + via: Vec, +} + +impl FoundSite { + fn literal(module: ModuleIdx, start: u32, via: Vec) -> Self { + FoundSite { module, start, bindings: vec![], top: false, via } + } +} + +/// Reads of a provider object through locals bound before it reaches a +/// Context: (site, (name, guards) list, escaped). +type SiteBindingReads = (usize, Vec<(String, Vec)>, bool); + +#[derive(Debug)] +enum ConsumerKind { + Binding(SymbolRef), + Names(Vec), +} + +#[derive(Debug)] +struct Consumer { + key: String, + kind: ConsumerKind, + chain: Vec, +} + +#[derive(Debug)] +struct GuardBinding { + symbol: SymbolRef, + declarator: Span, +} + +#[derive(Default, Debug)] +struct Demand { + all: bool, + names: FxHashSet, +} + +impl Demand { + fn add(&mut self, name: &str) -> bool { + if self.all || self.names.contains(name) { + return false; + } + self.names.insert(name.to_string()); + true + } + fn add_all(&mut self, other: &Demand) -> bool { + if self.all { + return false; + } + if other.all { + self.all = true; + return true; + } + let mut changed = false; + for name in &other.names { + changed |= self.add(name); + } + changed + } + fn set_all(&mut self) -> bool { + let changed = !self.all; + self.all = true; + changed + } + fn has(&self, name: &str) -> bool { + self.all || self.names.contains(name) + } +} + +/// Outcome of the pass, printed when `ROLLDOWN_EFFECT_SERVICE_SHAKING_REPORT` is set. +#[derive(Default, Debug)] +struct Report { + global_bailouts: Vec, + key_bailouts: Vec<(String, String)>, + removed: Vec, +} + +/// A reason the pass was turned off, reported as an `EFFECT_SERVICE_SHAKING` warning. +#[derive(Debug, Clone)] +struct Bailout { + reason: String, + /// Module and span start of the site. + site: Option<(ModuleIdx, u32)>, +} + +impl Bailout { + fn global(reason: String) -> Self { + Bailout { reason, site: None } + } + + fn at(module: ModuleIdx, offset: u32, reason: String) -> Self { + Bailout { reason, site: Some((module, offset)) } + } +} + +/// A Node builtin's name without the `node:` scheme. +fn bare_module_name(name: &str) -> &str { + name.strip_prefix("node:").unwrap_or(name) +} + +/// Facts shared by every module visit. +struct Shared<'l> { + symbols: &'l SymbolRefDb, + namespaces: FxHashMap, + resolved_exports: Vec>, + prefixes: Vec>, + /// API names (`Effect.map`) of the exports of trusted modules. + api_names: FxHashMap, + keys: FxHashMap, + key_creations: FxHashSet<(ModuleIdx, u32)>, + this_free: FxHashSet, + /// Bindings of code loaders imported from Node builtins, directly or through + /// re-exports: the import binding, or the external namespace. + code_loaders: FxHashSet, + /// Namespace and default imports of `node:process`. + capabilities: FxHashSet, + /// `const` bindings holding a constant string. + const_strings: FxHashMap, + /// Static member names of class-form keys. + key_statics: FxHashMap>, + /// Module-level functions that return only object literals: their module + /// and the literals' span starts. + builders: FxHashMap)>, +} + +impl Shared<'_> { + fn scoping(&self, module: ModuleIdx) -> &Scoping { + self.symbols.local_db(module).scoping() + } + + fn as_resolved(&self, symbol: SymbolRef) -> Resolved { + match self.namespaces.get(&symbol) { + Some(module) => Resolved::Namespace(*module), + None => Resolved::Symbol(symbol), + } + } + + fn resolve_ident(&self, module: ModuleIdx, ident: &IdentifierReference<'_>) -> Option { + let reference_id = ident.reference_id.get()?; + let symbol = self.scoping(module).get_reference(reference_id).symbol_id()?; + Some(self.as_resolved(self.symbols.canonical_ref_for((module, symbol).into()))) + } + + fn resolve_export(&self, module: ModuleIdx, name: &str) -> Option { + let symbol = self.resolved_exports.get(module.index())?.get(name)?; + Some(self.as_resolved(self.symbols.canonical_ref_for(*symbol))) + } + + fn resolve_expr(&self, module: ModuleIdx, expr: &Expression<'_>) -> Option { + match strip(expr) { + Expression::Identifier(ident) => self.resolve_ident(module, ident), + Expression::StaticMemberExpression(member) => { + let Resolved::Namespace(target) = self.resolve_expr(module, &member.object)? else { + return None; + }; + self.resolve_export(target, member.property.name.as_str()) + } + _ => None, + } + } + + fn api_name(&self, resolved: Option) -> Option<&str> { + let Resolved::Symbol(symbol) = resolved? else { return None }; + self.api_names.get(&symbol).map(String::as_str) + } + + fn api_of(&self, module: ModuleIdx, expr: &Expression<'_>) -> Option<&str> { + self.api_name(self.resolve_expr(module, expr)) + } + + /// The string a constant expression evaluates to: literals, templates and + /// `+` over them and over `const` bindings holding one. + fn const_string(&self, module: ModuleIdx, expr: &Expression<'_>) -> Option { + let mut out = String::new(); + for part in self.string_parts(module, expr)? { + match part { + StringPart::Literal(literal) => out.push_str(&literal), + StringPart::Binding(symbol) => out.push_str(self.const_strings.get(&symbol)?), + } + } + Some(out) + } + + fn string_parts(&self, module: ModuleIdx, expr: &Expression<'_>) -> Option> { + Some(match strip(expr) { + Expression::StringLiteral(literal) => { + vec![StringPart::Literal(literal.value.as_str()?.to_string())] + } + Expression::TemplateLiteral(template) => { + let mut parts = vec![]; + for (index, quasi) in template.quasis.iter().enumerate() { + parts.push(StringPart::Literal(quasi.value.cooked.as_ref()?.as_str()?.to_string())); + if let Some(expression) = template.expressions.get(index) { + parts.extend(self.string_parts(module, expression)?); + } + } + parts + } + Expression::BinaryExpression(binary) if binary.operator == BinaryOperator::Addition => { + let mut parts = self.string_parts(module, &binary.left)?; + parts.extend(self.string_parts(module, &binary.right)?); + parts + } + Expression::Identifier(ident) => { + let reference_id = ident.reference_id.get()?; + let symbol = self.scoping(module).get_reference(reference_id).symbol_id()?; + vec![StringPart::Binding(self.symbols.canonical_ref_for((module, symbol).into()))] + } + _ => return None, + }) + } + + fn key_of(&self, module: ModuleIdx, expr: &Expression<'_>) -> Option<&String> { + match self.resolve_expr(module, expr)? { + Resolved::Symbol(symbol) => self.keys.get(&symbol), + Resolved::Namespace(_) => None, + } + } + + /// A key creation `Context.Service("key")` or `Context.Service<..>()("key")`, + /// with the start of its callee: `None` when the expression does not create a key. + fn key_creation(&self, module: ModuleIdx, expr: &Expression<'_>) -> Option<(KeyCreation, u32)> { + let Expression::CallExpression(call) = strip(expr) else { return None }; + let callee = strip(&call.callee); + let api = self.api_of(module, callee); + let direct = matches!(api, Some("Context.Service" | "Context.Reference")); + let curried = matches!(callee, Expression::CallExpression(inner) + if inner.arguments.is_empty() + && self.api_of(module, &inner.callee) == Some("Context.Service")); + if !direct && !curried { + return None; + } + let key = match key_string(call) { + Some(key) => KeyCreation::Literal(key), + None => KeyCreation::Dynamic, + }; + Some((key, call.callee.span().start)) + } +} + +enum StringPart { + Literal(String), + Binding(SymbolRef), +} + +/// The literal key string of a key creation call, if it has one. +fn key_string(call: &CallExpression<'_>) -> Option { + match call.arguments.first() { + Some(Argument::StringLiteral(literal)) => literal.value.as_str().map(String::from), + _ => None, + } +} + +/// Whether a function may read its receiver: anywhere in its parameters +/// (defaults included) or body, except nested non-arrow functions. Any nested +/// class counts as a read. +fn reads_this(function: &Function<'_>) -> bool { + struct Finder(bool); + impl<'a> VisitJs<'a> for Finder { + fn visit_this_expression(&mut self, _it: &oxc::ast::ast::ThisExpression) { + self.0 = true; + } + fn visit_function(&mut self, _it: &Function<'a>, _flags: oxc::semantic::ScopeFlags) {} + // Heritage expressions and computed member names run with the enclosing + // receiver. Classes are not modelled, so any class counts as a read. + fn visit_class(&mut self, _it: &oxc::ast::ast::Class<'a>) { + self.0 = true; + } + } + let mut finder = Finder(false); + finder.visit_formal_parameters(&function.params); + if let Some(body) = &function.body { + finder.visit_function_body(body); + } else { + finder.0 = true; + } + finder.0 +} + +/// Whether a function body reads its own `arguments`, which aliases every +/// parameter without going through them. +fn reads_arguments(function_body: &oxc::ast::ast::FunctionBody<'_>) -> bool { + struct Finder(bool); + impl<'a> VisitJs<'a> for Finder { + fn visit_identifier_reference(&mut self, it: &IdentifierReference<'a>) { + self.0 |= it.name == "arguments"; + } + fn visit_function(&mut self, _it: &Function<'a>, _flags: oxc::semantic::ScopeFlags) {} + } + let mut finder = Finder(false); + finder.visit_function_body(function_body); + finder.0 +} + +/// Whether a class body mentions `this` or `super` anywhere, nested functions +/// included. +fn class_body_reads_this(class: &Class<'_>) -> bool { + struct Finder(bool); + impl VisitJs<'_> for Finder { + fn visit_this_expression(&mut self, _it: &oxc::ast::ast::ThisExpression) { + self.0 = true; + } + fn visit_super(&mut self, _it: &oxc::ast::ast::Super) { + self.0 = true; + } + } + let mut finder = Finder(false); + finder.visit_class_body(&class.body); + finder.0 +} + +/// The static member names of a class-form key's body, when every member is +/// static, has a constant name and leaves the inherited `Context.Service` +/// protocol (`of`, `key`, ...) alone; `None` otherwise. +fn class_key_statics(class: &Class<'_>) -> Option> { + class + .body + .body + .iter() + .map(|element| { + let (key, is_static, computed) = match element { + ClassElement::MethodDefinition(method) => (&method.key, method.r#static, method.computed), + ClassElement::PropertyDefinition(property) => { + (&property.key, property.r#static, property.computed) + } + ClassElement::AccessorProperty(accessor) => { + (&accessor.key, accessor.r#static, accessor.computed) + } + _ => return None, + }; + if !is_static || computed { + return None; + } + let name = key.static_name().and_then(|n| n.as_js_str().as_str().map(String::from))?; + let protocol = SERVICE_PROTOCOL.contains(&name.as_str()) + || INHERITED_MEMBERS.contains(&name.as_str()) + || name == "constructor" + || name.starts_with('~'); + (!protocol).then_some(name) + }) + .collect() +} + +/// Initialisers of a module's module-level `const` bindings, exported or not. +fn module_consts<'a>(program: &'a Program<'a>) -> FxHashMap> { + let mut consts = FxHashMap::default(); + for statement in &program.body { + let declaration = match statement { + Statement::VariableDeclaration(declaration) => declaration, + Statement::ExportDeclaration(export) => match &export.declaration { + Declaration::VariableDeclaration(declaration) => declaration, + _ => continue, + }, + _ => continue, + }; + if declaration.kind != VariableDeclarationKind::Const { + continue; + } + for declarator in &declaration.declarations { + if let (BindingPattern::BindingIdentifier(id), Some(init)) = + (&declarator.id, &declarator.init) + { + if let Some(symbol) = id.symbol_id.get() { + consts.insert(symbol, init); + } + } + } + } + consts +} + +/// Span starts of the object literals a function body returns, when every +/// return is an object literal. +fn object_returns(body: &FunctionBody<'_>) -> Option> { + let mut returns = Returns(vec![], true); + returns.statements(&body.statements); + if !returns.1 || returns.0.is_empty() { + return None; + } + returns + .0 + .iter() + .map(|value| match strip(value) { + Expression::ObjectExpression(object) => Some(object.span.start), + _ => None, + }) + .collect() +} + +/// Span starts of the object literals a function expression returns, when it +/// is a plain function or arrow and every return is an object literal. +fn builder_returns(function: &Expression<'_>) -> Option> { + match strip(function) { + Expression::ArrowFunctionExpression(f) if !f.r#async => match f.get_expression() { + Some(value) => match strip(value) { + Expression::ObjectExpression(object) => Some(vec![object.span.start]), + _ => None, + }, + None => f.body.as_function_body().and_then(object_returns), + }, + // A named function expression can hand itself out through its own name, + // which the reference check on the outer binding does not see. + Expression::FunctionExpression(f) if !f.r#async && !f.generator && f.id.is_none() => { + f.body.as_ref().and_then(|body| object_returns(body)) + } + _ => None, + } +} + +/// Return values of a function body, and whether every return was followed. +struct Returns<'b, 'a>(Vec<&'b Expression<'a>>, bool); +impl<'b, 'a> Returns<'b, 'a> { + fn statements(&mut self, statements: &'b [Statement<'a>]) { + for statement in statements { + self.statement(statement); + } + } + fn statement(&mut self, statement: &'b Statement<'a>) { + match statement { + Statement::ReturnStatement(ret) => match &ret.argument { + Some(argument) => self.0.push(argument), + None => self.1 = false, + }, + Statement::BlockStatement(block) => self.statements(&block.body), + Statement::IfStatement(stmt) => { + self.statement(&stmt.consequent); + if let Some(alternate) = &stmt.alternate { + self.statement(alternate); + } + } + Statement::TryStatement(stmt) => { + self.statements(&stmt.block.body); + if let Some(handler) = &stmt.handler { + self.statements(&handler.body.body); + } + if let Some(finalizer) = &stmt.finalizer { + self.statements(&finalizer.body); + } + } + // Returns inside loops, switches and labels are returns of the function too. + Statement::ForStatement(stmt) => self.statement(&stmt.body), + Statement::ForInStatement(stmt) => self.statement(&stmt.body), + Statement::ForOfStatement(stmt) => self.statement(&stmt.body), + Statement::WhileStatement(stmt) => self.statement(&stmt.body), + Statement::DoWhileStatement(stmt) => self.statement(&stmt.body), + Statement::LabeledStatement(stmt) => self.statement(&stmt.body), + Statement::SwitchStatement(stmt) => { + for case in &stmt.cases { + self.statements(&case.consequent); + } + } + Statement::WithStatement(_) => self.1 = false, + _ => {} + } + } +} + +/// Pass A: service keys and functions that never read `this`. +struct KeyCollector<'s, 'l> { + shared: &'s Shared<'l>, + module: ModuleIdx, + keys: Vec<(SymbolRef, KeyCreation, u32)>, + key_statics: Vec<(SymbolRef, FxHashSet)>, + builders: Vec<(SymbolRef, Vec)>, + this_free: Vec, + const_strings: Vec<(SymbolRef, Vec)>, + depth: usize, + kind: VariableDeclarationKind, +} + +impl<'a> VisitJs<'a> for KeyCollector<'_, '_> { + fn visit_function(&mut self, it: &Function<'a>, flags: oxc::semantic::ScopeFlags) { + if let Some(id) = &it.id { + if matches!(it.r#type, FunctionType::FunctionDeclaration) { + // A reassigned declaration may hold any function at runtime. + let scoping = self.shared.scoping(self.module); + if let Some(symbol) = id.symbol_id.get().filter(|s| !scoping.symbol_is_mutated(*s)) { + if !reads_this(it) { + self.this_free.push((self.module, symbol).into()); + } + if self.depth == 0 && !it.r#async && !it.generator { + if let Some(starts) = it.body.as_ref().and_then(|body| object_returns(body)) { + self.builders.push(((self.module, symbol).into(), starts)); + } + } + } + } + } + self.depth += 1; + walk_js::walk_function(self, it, flags); + self.depth -= 1; + } + + fn visit_arrow_function_expression(&mut self, it: &oxc::ast::ast::ArrowFunctionExpression<'a>) { + self.depth += 1; + walk_js::walk_arrow_function_expression(self, it); + self.depth -= 1; + } + + fn visit_variable_declaration(&mut self, it: &oxc::ast::ast::VariableDeclaration<'a>) { + let previous = self.kind; + self.kind = it.kind; + walk_js::walk_variable_declaration(self, it); + self.kind = previous; + } + + fn visit_variable_declarator(&mut self, it: &VariableDeclarator<'a>) { + if let (BindingPattern::BindingIdentifier(id), Some(init)) = (&it.id, &it.init) { + if let Some(symbol) = id.symbol_id.get() { + let symbol_ref: SymbolRef = (self.module, symbol).into(); + if self.kind == VariableDeclarationKind::Const { + if let Some(parts) = self.shared.string_parts(self.module, init) { + self.const_strings.push((symbol_ref, parts)); + } + match strip(init) { + Expression::ArrowFunctionExpression(_) => self.this_free.push(symbol_ref), + Expression::FunctionExpression(function) if !reads_this(function) => { + self.this_free.push(symbol_ref); + } + _ => {} + } + if self.depth == 0 { + if let Some((key, callee_start)) = self.shared.key_creation(self.module, init) { + self.keys.push((symbol_ref, key, callee_start)); + } + if let Some(starts) = builder_returns(init) { + self.builders.push((symbol_ref, starts)); + } + } + } + } + } + walk_js::walk_variable_declarator(self, it); + } + + /// A module-level `class K extends Context.Service<..>()("key") { ... }` is a + /// key declaration when its body never mentions `this` or `super`: static + /// members then reach the key only by name, which is checked like any use. + fn visit_class(&mut self, it: &Class<'a>) { + let super_class = it.heritage.as_ref().map(|heritage| &heritage.expression); + if let (0, Some(id), Some(super_class)) = (self.depth, &it.id, super_class) { + let scoping = self.shared.scoping(self.module); + let symbol = id.symbol_id.get().filter(|symbol| !scoping.symbol_is_mutated(*symbol)); + if let (Some(symbol), Some((key, callee_start))) = + (symbol, self.shared.key_creation(self.module, super_class)) + { + let statics = class_key_statics(it); + if let (oxc::ast::ast::ClassType::ClassDeclaration, false, Some(statics)) = + (it.r#type, class_body_reads_this(it), statics) + { + let symbol_ref: SymbolRef = (self.module, symbol).into(); + self.keys.push((symbol_ref, key, callee_start)); + self.key_statics.push((symbol_ref, statics)); + } + } + } + self.depth += 1; + walk_js::walk_class(self, it); + self.depth -= 1; + } +} + +/// Pass B: every use of keys, providers, consumers, guards and bailouts. +struct UseCollector<'s, 'l, 'a> { + shared: &'s Shared<'l>, + module: ModuleIdx, + trusted: bool, + path: Vec>, + guards: Vec, + top_stmt: usize, + refs: FxHashMap, + /// Uses of exported bindings through a module namespace, `ns.binding`. + namespace_refs: Vec<(SymbolRef, RefInfo)>, + /// Use-expression spans of key references already classified. + classified: FxHashSet, + /// Object literal (module, span start) recognised as provider sites -> site index. + site_spans: &'s mut FxHashMap<(ModuleIdx, u32), usize>, + sites: &'s mut Vec, + /// Initializers of this module's module-level `const` bindings. + module_consts: FxHashMap>, + /// Callee spans of constructor and builder calls followed into a provider. + accounted: Vec<(ModuleIdx, u32)>, + /// Callee span starts of keyed lookups whose keys were all resolved. + handled_lookups: FxHashSet, + /// Constructors being followed, and whether one was reached again. + constructors_in_progress: Vec, + constructor_cycle: bool, + consumers: Vec, + providers: Vec<(String, Container)>, + guard_bindings: Vec, + global_bailouts: Vec, + key_bailouts: Vec<(String, String)>, +} + +impl<'a> UseCollector<'_, '_, 'a> { + fn bail_global(&mut self, span: Span, reason: &str) { + self.global_bailouts.push(Bailout::at(self.module, span.start, reason.to_string())); + } + + /// A property read or written by `name`, `None` when the name is not constant. + /// Only constant string names can spell a code loader, so numbers and + /// well-known symbols need no case of their own. + fn check_member_name(&mut self, name: Option<&str>, span: Span) { + if let Some(name) = name.filter(|name| CODE_LOADERS.contains(name)) { + self.bail_global(span, &format!("`{name}` may run code outside the bundle")); + } + } + + /// A destructured property key. + fn check_property_key(&mut self, key: &PropertyKey<'a>, computed: bool, span: Span) { + let name = if computed { + key.as_expression().and_then(|expr| self.shared.const_string(self.module, expr)) + } else { + key.static_name().and_then(|n| n.as_js_str().as_str().map(String::from)) + }; + self.check_destructured_name(name.as_deref(), span); + } + + fn check_destructured_name(&mut self, name: Option<&str>, span: Span) { + self.check_member_name(name, span); + if name == Some("getOwnPropertyDescriptor") { + self.bail_global(span, "`getOwnPropertyDescriptor` used as a value"); + } + } + + /// `Reflect.get` and `getOwnPropertyDescriptor` read the property named by + /// their second argument, so a constant loader name there is checked like a + /// member name. `Reflect.get` is recognised on the global `Reflect`, bare or + /// qualified (`globalThis.Reflect`). `getOwnPropertyDescriptor` is matched on + /// any receiver: a conservative fallback that covers aliases of `Object` the + /// pass cannot track, and also matches user methods with that name. Used + /// other than by a call, or with a spread before the key, the name they will + /// read is unknown. + fn check_reflective_read(&mut self, object: &Expression<'a>, name: &str, span: Span) { + if name != "getOwnPropertyDescriptor" && !(name == "get" && self.is_global_reflect(object)) { + return; + } + let call = match self.parent(0) { + Some(AstKind::CallExpression(call)) if call.callee.span() == span => Some(( + call.span, + call + .arguments + .iter() + .take(2) + .any(|argument| matches!(argument, Argument::SpreadElement(_))), + call + .arguments + .get(1) + .and_then(Argument::as_expression) + .and_then(|key| self.shared.const_string(self.module, key)), + )), + _ => None, + }; + match call { + Some((call_span, true, _)) => { + self.bail_global(call_span, &format!("`{name}` called with a spread before the key")); + } + Some((call_span, false, key)) => self.check_member_name(key.as_deref(), call_span), + None => self.bail_global(span, &format!("`{name}` used as a value")), + } + } + + /// The global `Reflect`: the unresolved identifier, or a constant member + /// named `Reflect` on a global object (`globalThis.Reflect`). + fn is_global_reflect(&self, expr: &Expression<'a>) -> bool { + match strip(expr) { + Expression::Identifier(ident) => ident.name == "Reflect" && self.is_global_value(expr), + _ => self + .constant_member(expr) + .is_some_and(|(object, name)| name == "Reflect" && self.on_global_object(object)), + } + } + + /// Whether `expr` is the global object, such as `globalThis` or + /// `globalThis.self`, through constant names. + fn on_global_object(&self, expr: &Expression<'a>) -> bool { + match strip(expr) { + Expression::Identifier(ident) => { + GLOBAL_OBJECTS.contains(&ident.name.as_str()) && self.is_global_value(expr) + } + _ => self.constant_member(expr).is_some_and(|(object, name)| { + GLOBAL_OBJECTS.contains(&name.as_str()) && self.on_global_object(object) + }), + } + } + + /// A static member read, or a computed one with a constant name: the object + /// and the name. + fn constant_member<'b>(&self, expr: &'b Expression<'a>) -> Option<(&'b Expression<'a>, String)> { + match strip(expr) { + Expression::StaticMemberExpression(member) => { + Some((&member.object, member.property.name.to_string())) + } + Expression::ComputedMemberExpression(member) => { + Some((&member.object, self.shared.const_string(self.module, &member.expression)?)) + } + _ => None, + } + } + + /// A static member, or a computed one with a constant name, read or written + /// in untrusted code: code-loader names, reflective reads and the global + /// `Reflect` used as a value. + fn check_member(&mut self, object: &Expression<'a>, name: Option<&str>, span: Span) { + self.check_member_name(name, span); + if let Some(name) = name { + self.check_reflective_read(object, name, span); + if name == "Reflect" && self.on_global_object(object) { + self.check_reflect_value(span); + } + } + } + + /// The global `Reflect` other than as the object of a member read or a + /// `typeof` operand, such as `const { get } = Reflect`, hides which name + /// `Reflect.get` will read. + fn check_reflect_value(&mut self, span: Span) { + let allowed = match self.parent(0) { + Some(AstKind::StaticMemberExpression(member)) => member.object.span() == span, + Some(AstKind::ComputedMemberExpression(member)) => member.object.span() == span, + Some(AstKind::UnaryExpression(unary)) => unary.operator == UnaryOperator::Typeof, + _ => false, + }; + if !allowed { + self.bail_global(span, "`Reflect` used as a value"); + } + } + + /// Code loaders and the host values that lead to them (A2). + fn check_host_reference(&mut self, it: &IdentifierReference<'a>) { + let local = it + .reference_id + .get() + .and_then(|reference| self.shared.scoping(self.module).get_reference(reference).symbol_id()) + .map(|symbol| -> SymbolRef { (self.module, symbol).into() }); + let bindings = local.map(|local| (local, self.shared.symbols.canonical_ref_for(local))); + let bound_to = |set: &FxHashSet| { + bindings.is_some_and(|(local, canonical)| set.contains(&local) || set.contains(&canonical)) + }; + let typeof_operand = matches!(self.parent(0), Some(AstKind::UnaryExpression(unary)) + if unary.operator == UnaryOperator::Typeof); + if bound_to(&self.shared.code_loaders) { + if !typeof_operand { + self.bail_global(it.span, "host operation that loads code"); + } + return; + } + let global_capability = local.is_none() + && it.reference_id.get().is_some() + && CAPABILITY_GLOBALS.contains(&it.name.as_str()); + if !global_capability && !bound_to(&self.shared.capabilities) { + return; + } + // Follow constant member names while they still lead to a capability + // (`globalThis.process`); any other member is a plain read or call. + let mut span = it.span; + let mut depth = 0; + loop { + let name = match self.parent(depth) { + Some(AstKind::StaticMemberExpression(member)) if member.object.span() == span => { + Some((member.property.name.to_string(), member.span)) + } + Some(AstKind::ComputedMemberExpression(member)) if member.object.span() == span => { + match self.shared.const_string(self.module, &member.expression) { + Some(name) => Some((name, member.span)), + None => { + self.bail_global(it.span, "host capability read by a non-constant name"); + return; + } + } + } + _ => None, + }; + match name { + Some((name, member_span)) if CAPABILITY_GLOBALS.contains(&name.as_str()) => { + span = member_span; + depth += 1; + } + Some(_) => return, + None => break, + } + } + let typeof_operand = matches!(self.parent(depth), Some(AstKind::UnaryExpression(unary)) + if unary.operator == UnaryOperator::Typeof); + if !typeof_operand { + self.bail_global(it.span, "host capability used as a value"); + } + } + + /// Whether a provider property's identifier value is initialised wherever the + /// provider object is built, so reading it cannot throw. Function declarations + /// and `var` always are; a `const`, `let` or class must be declared earlier in + /// the source with no hoisted function declaration between, which could run + /// the site first, and not in another case of a switch the site is in, since + /// jumping to a case skips the cases before it, and not around the site: inside + /// its own declaration, parameter list, catch parameter or loop head (while + /// the loop's right-hand side runs) a binding is uninitialised. An import may be + /// uninitialised through a module cycle, even one back to its own module. + fn initialized_at(&self, value: &Expression<'a>, site: u32) -> bool { + let Expression::Identifier(ident) = value else { return false }; + let Some(reference) = ident.reference_id.get() else { return false }; + let scoping = self.shared.scoping(self.module); + let Some(symbol) = scoping.get_reference(reference).symbol_id() else { return false }; + let flags = scoping.symbol_flags(symbol); + if flags.contains(SymbolFlags::Import) { + return false; + } + let declared = scoping.symbol_span(symbol); + // The site runs the right-hand side of a loop whose head declares the binding. + let in_loop_head = |left: Span, right: Span| { + left.contains_inclusive(declared) && (right.start..right.end).contains(&site) + }; + // Parameters share the `var` flag, but a default runs before its own + // parameter and the later ones are initialised. + if self.path.iter().any(|kind| { + matches!(kind, AstKind::FormalParameters(params) if params.span.contains_inclusive(declared)) + }) { + return false; + } + if flags.intersects(SymbolFlags::Function | SymbolFlags::FunctionScopedVariable) { + return true; + } + declared.end <= site + && self.path.iter().all(|kind| match kind { + AstKind::Function(function) => { + function.r#type != FunctionType::FunctionDeclaration + || function.span.contains_inclusive(declared) + } + // Inside the binding's own declaration, directly or in code it runs + // (an immediately invoked function, a class heritage), the binding is + // still in its temporal dead zone. + AstKind::VariableDeclarator(declarator) => { + !declarator.id.span().contains_inclusive(declared) + } + AstKind::Class(class) => { + class.id.as_ref().is_none_or(|id| id.symbol_id.get() != Some(symbol)) + } + // A catch binding is uninitialised while its own pattern (defaults + // included) is evaluated. + AstKind::CatchParameter(param) => !param.pattern.span().contains_inclusive(declared), + // A lexical loop-head binding is uninitialised while the loop's + // right-hand side runs. + AstKind::ForOfStatement(stmt) => !in_loop_head(stmt.left.span(), stmt.right.span()), + AstKind::ForInStatement(stmt) => !in_loop_head(stmt.left.span(), stmt.right.span()), + _ => true, + }) + && self.path.windows(2).all(|pair| match pair { + [AstKind::SwitchStatement(switch), AstKind::SwitchCase(case)] => { + !switch.span.contains_inclusive(declared) || case.span.contains_inclusive(declared) + } + _ => true, + }) + } + + /// An unresolved global, such as `Map`. + fn is_global_value(&self, expr: &Expression<'_>) -> bool { + matches!(strip(expr), Expression::Identifier(ident) + if ident.reference_id.get().is_some() && self.shared.resolve_ident(self.module, ident).is_none()) + } + + /// Whether the member expression at `span` is read in place: the object of + /// a further member read that is not written. + fn read_in_place(&self, span: Span) -> bool { + match self.parent(0) { + Some(AstKind::StaticMemberExpression(member)) if member.object.span() == span => { + !self.is_write_target(1) + } + Some(AstKind::ComputedMemberExpression(member)) if member.object.span() == span => { + !self.is_write_target(1) + } + _ => false, + } + } + + fn bail_key(&mut self, key: &str, span: Span, reason: &str) { + self + .key_bailouts + .push((key.to_string(), format!("{reason} (module {:?} at {})", self.module, span.start))); + } + + /// Ancestors of the current node, innermost first, skipping wrappers. + fn parent(&self, depth: usize) -> Option<&AstKind<'a>> { + self.path.iter().rev().nth(depth) + } + + /// Where a container value at `span`, whose parent is `self.path[index]`, flows. + fn container_from(&self, span: Span, mut index: usize) -> Container { + let mut current = span; + loop { + let Some(parent) = self.path.get(index) else { return Container::Escape }; + match parent { + AstKind::ParenthesizedExpression(_) => { + current = parent.span(); + } + AstKind::CallExpression(call) => { + if call.callee.span() == current { + return Container::Escape; + } + let api = self.shared.api_of(self.module, &call.callee); + match api { + Some("Effect.provide" | "Layer.launch") => return Container::Terminal, + Some("Layer.merge" | "Layer.mergeAll" | "Layer.provide" | "Layer.provideMerge") => { + if call.arguments.len() == 1 && api != Some("Layer.mergeAll") { + // A curried combinator must be applied right away. + let Some(AstKind::CallExpression(outer)) = + index.checked_sub(1).and_then(|i| self.path.get(i)) + else { + return Container::Escape; + }; + if outer.callee.span() != call.span { + return Container::Escape; + } + current = outer.span; + index -= 1; + } else { + current = call.span; + } + } + _ => return Container::Escape, + } + } + // `layer.pipe(Layer.provide(a), ...)` with curried Layer combinators. + AstKind::StaticMemberExpression(member) + if member.object.span() == current && member.property.name == "pipe" => + { + let Some(AstKind::CallExpression(call)) = + index.checked_sub(1).and_then(|i| self.path.get(i)) + else { + return Container::Escape; + }; + let combinators = !call.arguments.is_empty() + && call.arguments.iter().all(|argument| { + matches!(argument.as_expression().map(strip), Some(Expression::CallExpression(inner)) + if inner.arguments.len() == 1 + && self.shared.api_of(self.module, &inner.callee) + .is_some_and(|api| PIPED_LAYER_COMBINATORS.contains(&api))) + }); + if call.callee.span() != member.span || !combinators { + return Container::Escape; + } + current = call.span; + index -= 1; + } + // The body of `const f = (..) => value`, or `return value` directly in + // a module-level function. + AstKind::ArrowFunctionExpression(arrow) + if arrow.get_expression().is_some_and(|body| body.span() == current) => + { + return if arrow.r#async { Container::Escape } else { self.factory(arrow.span, index) }; + } + AstKind::ReturnStatement(statement) + if statement.argument.as_ref().is_some_and(|argument| argument.span() == current) => + { + return match ( + index.checked_sub(1).and_then(|i| self.path.get(i)), + index.checked_sub(2).and_then(|i| self.path.get(i)), + ) { + (Some(AstKind::FunctionBody(_)), Some(AstKind::ArrowFunctionExpression(arrow))) + if !arrow.r#async => + { + self.factory(arrow.span, index - 2) + } + (Some(AstKind::FunctionBody(_)), Some(AstKind::Function(function))) + if !function.r#async && !function.generator => + { + self.factory(function.span, index - 2) + } + _ => Container::Escape, + }; + } + AstKind::VariableDeclarator(declarator) => { + let is_init = declarator.init.as_ref().is_some_and(|init| init.span() == current); + let kind = match index.checked_sub(1).and_then(|i| self.path.get(i)) { + Some(AstKind::VariableDeclaration(declaration)) => declaration.kind, + _ => VariableDeclarationKind::Var, + }; + return match (&declarator.id, is_init, kind) { + (BindingPattern::BindingIdentifier(id), true, VariableDeclarationKind::Const) => { + id.symbol_id.get().map_or(Container::Escape, |symbol| { + Container::Binding( + self.shared.symbols.canonical_ref_for((self.module, symbol).into()), + ) + }) + } + _ => Container::Escape, + }; + } + _ => return Container::Escape, + } + let Some(next) = index.checked_sub(1) else { return Container::Escape }; + index = next; + } + } + + /// The function at ancestor `index`, with span `function`, as a container: + /// a module-level `const` or function declaration, never reassigned, in an + /// untrusted module. + fn factory(&self, function: Span, index: usize) -> Container { + // Only outside the trusted packages: A3 does not cover how Effect's own + // modules read Effect's own services. + if self.trusted { + return Container::Escape; + } + let module_level = |i: usize| match self.path.get(i) { + Some(AstKind::Program(_)) => true, + Some(AstKind::ExportDeclaration(_)) => { + matches!(i.checked_sub(1).and_then(|j| self.path.get(j)), Some(AstKind::Program(_))) + } + _ => false, + }; + let scoping = self.shared.scoping(self.module); + let symbol = match self.path.get(index) { + Some(AstKind::Function(f)) if f.r#type == FunctionType::FunctionDeclaration => f + .id + .as_ref() + .and_then(|id| id.symbol_id.get()) + .filter(|_| index.checked_sub(1).is_some_and(module_level)), + _ => match ( + index.checked_sub(1).and_then(|i| self.path.get(i)), + index.checked_sub(2).and_then(|i| self.path.get(i)), + ) { + (Some(AstKind::VariableDeclarator(declarator)), Some(AstKind::VariableDeclaration(d))) + if d.kind == VariableDeclarationKind::Const + && declarator.init.as_ref().is_some_and(|init| strip(init).span() == function) + && index.checked_sub(3).is_some_and(module_level) => + { + match &declarator.id { + BindingPattern::BindingIdentifier(id) => id.symbol_id.get(), + _ => None, + } + } + _ => None, + }, + }; + match symbol.filter(|symbol| !scoping.symbol_is_mutated(*symbol)) { + Some(symbol) => { + Container::Factory(self.shared.symbols.canonical_ref_for((self.module, symbol).into())) + } + None => Container::Escape, + } + } + + /// Where the result of calling the expression at `span`, whose parent is + /// `self.path[index]`, flows: `None` when it is not called directly. + fn call_result(&self, span: Span, index: usize) -> Option { + match self.path.get(index) { + Some(AstKind::CallExpression(call)) if call.callee.span() == span => { + Some(index.checked_sub(1).map_or(Container::Escape, |i| self.container_from(call.span, i))) + } + _ => None, + } + } + + /// Provider objects reachable from an Effect expression in the base case. + /// Returns false when some source is not a recognised object literal. + fn effect_sites(&mut self, expr: &Expression<'a>, found: &mut Vec) -> bool { + let Expression::CallExpression(call) = strip(expr) else { return false }; + let args = &call.arguments; + match self.shared.api_of(self.module, &call.callee) { + Some("Effect.succeed") if args.len() == 1 => { + args[0].as_expression().is_some_and(|value| self.value_sites(value, found)) + } + Some("Effect.sync") if args.len() == 1 => { + args[0].as_expression().is_some_and(|f| self.return_sites(f, false, found)) + } + Some("Effect.gen") if !args.is_empty() => { + args[args.len() - 1].as_expression().is_some_and(|f| self.return_sites(f, true, found)) + } + Some("Effect.acquireRelease") if args.len() == 2 => { + let mut acquired = vec![]; + let complete = args[0].as_expression().is_some_and(|e| self.effect_sites(e, &mut acquired)); + // The release callback receives the acquired object. Only a single + // plain parameter without a default is followed; anything else (more + // parameters, defaults, a rest parameter, a pattern or `arguments`) + // keeps the whole object. + let (params, reads_args) = match args[1].as_expression().map(strip) { + Some(Expression::ArrowFunctionExpression(f)) => (Some(&f.params), false), + Some(Expression::FunctionExpression(f)) => { + (Some(&f.params), f.body.as_ref().is_none_or(|body| reads_arguments(body))) + } + _ => (None, false), + }; + let simple = |params: &oxc::ast::ast::FormalParameters<'a>| { + params.rest.is_none() + && params.items.len() <= 1 + && params.items.iter().all(|param| param.initializer.is_none()) + }; + let (binding, top): (Option, bool) = match params { + Some(params) if simple(params) && !reads_args => match params.items.first() { + None => (None, false), + Some(param) => match ¶m.pattern { + BindingPattern::BindingIdentifier(id) => { + (id.symbol_id.get().map(|s| (self.module, s).into()), id.symbol_id.get().is_none()) + } + _ => (None, true), + }, + }, + _ => (None, true), + }; + // Nested acquisitions keep the readers of every level. + for mut site in acquired { + site.bindings.extend(binding); + site.top |= top; + found.push(site); + } + complete + } + // `make(args)`, where `make` is a module-level `Effect.fn` constructor + // outside the trusted packages. + _ => { + if self.trusted { + return false; + } + let Some(Resolved::Symbol(symbol)) = self.shared.resolve_expr(self.module, &call.callee) + else { + return false; + }; + let Some(generator) = self.constructor_generator(symbol) else { return false }; + // A constructor returning its own result: stop at the cycle, and keep + // every property of the provider. + if self.constructors_in_progress.contains(&symbol) { + self.constructor_cycle = true; + return false; + } + self.constructors_in_progress.push(symbol); + let mut returned = vec![]; + let complete = self.return_sites(generator, true, &mut returned); + self.constructors_in_progress.pop(); + self.accounted.push((self.module, call.callee.span().start)); + for mut site in returned { + site.via.push(symbol); + found.push(site); + } + complete + } + } + } + + /// The generator of a module-level `const make = Effect.fn(function* () {..}, ...)` + /// in this module, when every pipeable only changes the constructor's context. + fn constructor_generator(&self, symbol: SymbolRef) -> Option<&'a Expression<'a>> { + if symbol.owner != self.module { + return None; + } + let Expression::CallExpression(call) = strip(self.module_consts.get(&symbol.symbol)?) else { + return None; + }; + if !matches!( + self.shared.api_of(self.module, &call.callee), + Some("Effect.fn" | "Effect.fnUntraced") + ) { + return None; + } + let (first, pipeables) = call.arguments.split_first()?; + let generator = first.as_expression()?; + if !matches!(strip(generator), Expression::FunctionExpression(f) if f.generator) { + return None; + } + pipeables.iter().all(|pipeable| self.is_context_pipeable(pipeable)).then_some(generator) + } + + /// `Effect.updateService(K, f)` and similar, directly or through a + /// module-level `const` of this module. + fn is_context_pipeable(&self, pipeable: &Argument<'a>) -> bool { + let Some(mut expr) = pipeable.as_expression() else { return false }; + if let Expression::Identifier(ident) = strip(expr) { + let local = ident.reference_id.get().and_then(|reference| { + self.shared.scoping(self.module).get_reference(reference).symbol_id() + }); + match local.and_then(|symbol| self.module_consts.get(&symbol)) { + Some(init) => expr = init, + None => return false, + } + } + matches!(strip(expr), Expression::CallExpression(call) + if self.shared.api_of(self.module, &call.callee).is_some_and(|api| CONTEXT_PIPEABLES.contains(&api))) + } + + fn return_sites( + &mut self, + function: &Expression<'a>, + generator: bool, + found: &mut Vec, + ) -> bool { + let body = match strip(function) { + Expression::ArrowFunctionExpression(f) if !generator && !f.r#async => { + match f.body.as_function_body() { + Some(body) => body, + None => return f.get_expression().is_some_and(|value| self.value_sites(value, found)), + } + } + Expression::FunctionExpression(f) if f.generator == generator && !f.r#async => { + // A named function expression can hand itself out through its own + // name, and each call builds another object from the same literal. + // A name nothing references, kept for stack traces, is harmless. + let scoping = self.shared.scoping(self.module); + let referenced = f.id.as_ref().is_some_and(|id| { + id.symbol_id + .get() + .is_none_or(|symbol| !scoping.get_resolved_reference_ids(symbol).is_empty()) + }); + let Some(body) = f.body.as_ref().filter(|_| !referenced) else { return false }; + body + } + _ => return false, + }; + let mut returns = Returns(vec![], true); + returns.statements(&body.statements); + let mut complete = returns.1 && !returns.0.is_empty(); + for value in returns.0 { + complete &= match strip(value) { + // `return yield* effect` in an Effect generator returns its result. + Expression::YieldExpression(yielded) if generator && yielded.delegate => { + yielded.argument.as_ref().is_some_and(|effect| self.effect_sites(effect, found)) + } + _ => self.value_sites(value, found), + }; + } + complete + } + + fn value_sites(&mut self, value: &Expression<'a>, found: &mut Vec) -> bool { + match strip(value) { + Expression::ObjectExpression(object) => { + found.push(FoundSite::literal(self.module, object.span.start, vec![])); + true + } + Expression::CallExpression(call) => { + // `build(args)`, where `build` is a module-level function returning object literals. + let resolved = + self.shared.resolve_expr(self.module, &call.callee).filter(|_| !self.trusted); + if let Some(Resolved::Symbol(symbol)) = resolved { + if let Some((module, starts)) = self.shared.builders.get(&symbol) { + self.accounted.push((self.module, call.callee.span().start)); + for start in starts { + found.push(FoundSite::literal(*module, *start, vec![symbol])); + } + return true; + } + } + // `Key.of(value)` is the identity. + let Expression::StaticMemberExpression(member) = strip(&call.callee) else { return false }; + if member.property.name != "of" || self.shared.key_of(self.module, &member.object).is_none() + { + return false; + } + match call.arguments.first().and_then(Argument::as_expression) { + Some(argument) if call.arguments.len() == 1 => self.value_sites(argument, found), + _ => false, + } + } + _ => false, + } + } + + /// Registers the provider objects of `Layer.succeed(K, value)` / `Layer.effect(K, effect)`. + /// Sources that are not recognised object literals are simply not sites, so + /// whether every source was followed does not matter here. + fn provider(&mut self, key: &str, kind: &str, value: &Expression<'a>, container: Container) { + let mut found = vec![]; + self.constructor_cycle = false; + if kind == "Layer.succeed" { + self.value_sites(value, &mut found); + } else { + self.effect_sites(value, &mut found); + } + let cycle = std::mem::take(&mut self.constructor_cycle); + for found in found { + let index = *self.site_spans.entry((found.module, found.start)).or_insert_with(|| { + self.sites.push(Site { + module: found.module, + keys: FxHashSet::default(), + props: vec![], + top: false, + bindings: vec![], + via: vec![], + }); + self.sites.len() - 1 + }); + let site = &mut self.sites[index]; + site.keys.insert(key.to_string()); + site.top |= found.top || cycle; + site.bindings.extend(found.bindings); + for symbol in found.via { + if !site.via.contains(&symbol) { + site.via.push(symbol); + } + } + } + self.providers.push((key.to_string(), container)); + } + + fn is_effect_generator(&self, yield_depth: usize) -> bool { + // The nearest function around the `yield*` must be a generator passed to + // `Effect.gen`, `Effect.fn` or `Effect.fnUntraced`. + let mut iter = self.path.iter().rev().skip(yield_depth); + while let Some(kind) = iter.next() { + match kind { + AstKind::Function(function) => { + if !function.generator { + return false; + } + return match iter.next() { + Some(AstKind::CallExpression(call)) => { + matches!( + self.shared.api_of(self.module, &call.callee), + Some("Effect.gen" | "Effect.fn" | "Effect.fnUntraced") + ) && call.arguments.iter().any(|arg| arg.span() == function.span) + } + _ => false, + }; + } + AstKind::ArrowFunctionExpression(_) => return false, + _ => {} + } + } + false + } + + fn record_reference(&mut self, ident: &IdentifierReference<'a>) { + let Some(reference_id) = ident.reference_id.get() else { return }; + let scoping = self.shared.scoping(self.module); + let symbol = scoping.get_reference(reference_id).symbol_id(); + let root_symbol = + symbol.filter(|symbol| scoping.symbol_scope_id(*symbol) == scoping.root_scope_id()); + // Member reads only matter for locals: consumer and release bindings. + let member = match self.parent(0) { + Some(AstKind::StaticMemberExpression(member)) + if member.object.span() == ident.span && symbol.is_some() && root_symbol.is_none() => + { + Some((member.property.name.as_str().to_string(), self.is_write_target(1))) + } + _ => None, + }; + let container = self.container_from(ident.span, self.path.len() - 1); + let call_result = self.call_result(ident.span, self.path.len() - 1); + // `ns.binding` is a use of the exported binding, from the member's position. + if let Some(symbol) = symbol { + let canonical = self.shared.symbols.canonical_ref_for((self.module, symbol).into()); + if let Resolved::Namespace(target) = self.shared.as_resolved(canonical) { + if let NamespaceChain::Export { symbol: export, span, depth } = + self.namespace_chain(ident.span, target) + { + let (container, call_result) = match self.path.len().checked_sub(2 + depth) { + Some(index) => (self.container_from(span, index), self.call_result(span, index)), + None => (Container::Escape, None), + }; + self.namespace_refs.push(( + export, + RefInfo { + module: self.module, + span, + top_stmt: self.top_stmt, + chain: self.guards.clone(), + member: None, + container, + call_result, + root_symbol: None, + }, + )); + } + } + } + self.refs.insert( + reference_id, + RefInfo { + module: self.module, + span: ident.span, + top_stmt: self.top_stmt, + chain: self.guards.clone(), + member, + container, + call_result, + root_symbol, + }, + ); + } + + /// Follows `ns.a.b...` from an identifier resolving to a namespace through + /// every namespace hop. + fn namespace_chain(&self, ident: Span, mut target: ModuleIdx) -> NamespaceChain { + let mut current = ident; + let mut depth = 0; + loop { + match self.parent(depth) { + Some(AstKind::StaticMemberExpression(member)) if member.object.span() == current => { + match self.shared.resolve_export(target, member.property.name.as_str()) { + Some(Resolved::Symbol(symbol)) => { + return NamespaceChain::Export { symbol, span: member.span, depth }; + } + Some(Resolved::Namespace(next)) => { + target = next; + current = member.span; + depth += 1; + } + None => return NamespaceChain::Unresolved, + } + } + _ => return NamespaceChain::Value(current), + } + } + } + + /// Whether the member expression at ancestor `depth - 1` is written. + fn is_write_target(&self, depth: usize) -> bool { + match self.parent(depth) { + Some( + AstKind::AssignmentExpression(_) + | AstKind::UpdateExpression(_) + | AstKind::ArrayAssignmentTarget(_) + | AstKind::ObjectAssignmentTarget(_) + | AstKind::AssignmentTargetWithDefault(_) + | AstKind::AssignmentTargetPropertyProperty(_) + | AstKind::AssignmentTargetRest(_) + | AstKind::ForInStatement(_) + | AstKind::ForOfStatement(_), + ) => { + // Reads on the right-hand side of an assignment are still reads. + match self.parent(depth) { + Some(AstKind::AssignmentExpression(assign)) => { + let member = self.parent(depth - 1).map(GetSpan::span); + member.is_some_and(|span| assign.left.span().contains_inclusive(span)) + } + Some(AstKind::ForInStatement(stmt)) => { + self.parent(depth - 1).is_some_and(|m| stmt.left.span().contains_inclusive(m.span())) + } + Some(AstKind::ForOfStatement(stmt)) => { + self.parent(depth - 1).is_some_and(|m| stmt.left.span().contains_inclusive(m.span())) + } + _ => true, + } + } + Some(AstKind::UnaryExpression(unary)) => unary.operator.is_delete(), + _ => false, + } + } + + fn check_untrusted_reference( + &mut self, + ident: &IdentifierReference<'a>, + resolved: Option, + ) { + let name = ident.name.as_str(); + match resolved { + None if ident.reference_id.get().is_some() => match name { + "eval" | "Function" | "require" => { + self.bail_global(ident.span, &format!("`{name}` may run code outside the bundle")); + } + _ => {} + }, + Some(Resolved::Namespace(target)) => match self.namespace_chain(ident.span, target) { + NamespaceChain::Export { symbol, span, .. } => { + self.check_api(Some(Resolved::Symbol(symbol)), span); + } + // Every export of the module, Layers included, may escape through it. + NamespaceChain::Value(span) => self.bail_global(span, "module namespace used as a value"), + NamespaceChain::Unresolved => {} + }, + Some(Resolved::Symbol(_)) => self.check_api(resolved, ident.span), + None => {} + } + } + + /// Untrusted reference to a trusted export. + fn check_api(&mut self, resolved: Option, span: Span) { + let Some(Resolved::Symbol(symbol)) = resolved else { return }; + if self.shared.keys.contains_key(&symbol) { + return; + } + let Some(name) = self.shared.api_name(resolved).map(str::to_string) else { return }; + // Any other use, such as an alias, creates keys the pass cannot see, and + // keys with the same string alias at runtime. + if matches!(name.as_str(), "Context.Service" | "Context.Reference") + && !self.shared.key_creations.contains(&(self.module, span.start)) + { + self.bail_global(span, &format!("`{name}` used other than to declare a service key")); + } else if CONTEXT_INTERNAL_APIS.contains(&name.as_str()) { + self.bail_global(span, &format!("`{name}` reads Context internals")); + } else if KEYED_LOOKUPS.contains(&name.as_str()) && !self.handled_lookups.contains(&span.start) + { + // A lookup the pass does not model, possibly by a key it does not track. + self.bail_global(span, &format!("`{name}` looks a service up other than by `yield*`")); + } + } + + fn classify_key_reference(&mut self, key: &str, use_span: Span, use_depth: usize) { + if !self.classified.contains(&use_span.start) { + let parent = match self.parent(use_depth) { + Some(kind) => format!("{kind:?}").split('(').next().unwrap_or_default().to_string(), + None => "program".to_string(), + }; + // Opaque code holding a key may change its key string, which moves + // lookups to another service, so outside trusted modules this is global. + if self.trusted { + self.bail_key(key, use_span, &format!("service key used in {parent}")); + } else { + self.bail_global(use_span, &format!("service key `{key}` used in {parent}")); + } + } + } +} + +impl<'a> VisitJs<'a> for UseCollector<'_, '_, 'a> { + fn enter_node(&mut self, kind: AstKind<'a>) { + self.path.push(kind); + } + + fn leave_node(&mut self, _kind: AstKind<'a>) { + self.path.pop(); + } + + fn visit_statements(&mut self, it: &ArenaVec<'a, Statement<'a>>) { + let is_program = matches!(self.path.last(), Some(AstKind::Program(_))); + for (index, statement) in it.iter().enumerate() { + if is_program { + self.top_stmt = index + 1; + } + self.visit_statement(statement); + } + } + + fn visit_yield_expression(&mut self, it: &YieldExpression<'a>) { + if let (true, Some(argument)) = (it.delegate, &it.argument) { + if let Some(key) = self.shared.key_of(self.module, argument).cloned() { + self.classified.insert(strip(argument).span().start); + let in_effect = self.is_effect_generator(0); + // Skip parentheses around the `yield*`. + let mut depth = 0; + let mut use_span = it.span; + while let Some(AstKind::ParenthesizedExpression(paren)) = self.parent(depth) { + use_span = paren.span; + depth += 1; + } + let target = match self.parent(depth) { + // `(yield* K).name`, e.g. after Rolldown inlined a single-use const. + Some(AstKind::StaticMemberExpression(member)) if member.object.span() == use_span => { + (!self.is_write_target(depth + 1)) + .then(|| ConsumerKind::Names(vec![member.property.name.as_str().to_string()])) + } + Some(AstKind::VariableDeclarator(declarator)) + if matches!(self.parent(depth + 1), Some(AstKind::VariableDeclaration(d)) if d.kind == VariableDeclarationKind::Const) + && declarator.init.as_ref().is_some_and(|init| strip(init).span() == it.span) => + { + match &declarator.id { + BindingPattern::BindingIdentifier(id) => { + id.symbol_id.get().map(|symbol| ConsumerKind::Binding((self.module, symbol).into())) + } + BindingPattern::ObjectPattern(pattern) if pattern.rest.is_none() => pattern + .properties + .iter() + .map(|property| { + if property.computed { + None + } else { + property + .key + .static_name() + .and_then(|n| n.as_js_str().as_str().map(String::from)) + } + }) + .collect::>>() + .map(ConsumerKind::Names), + _ => None, + } + } + _ => None, + }; + match (in_effect, target) { + (true, Some(kind)) => { + if let ConsumerKind::Names(names) = &kind { + if names.iter().any(|name| INHERITED_MEMBERS.contains(&name.as_str())) { + self.bail_key(&key, it.span, "inherited member destructured"); + } + } + self.consumers.push(Consumer { key, kind, chain: self.guards.clone() }); + } + // A non-Effect driver receives the key itself. + (false, _) if self.trusted => { + self.bail_key(&key, it.span, "`yield*` outside an Effect generator"); + } + (false, _) => { + self.bail_global(it.span, "service key yielded outside an Effect generator"); + } + (true, None) => { + self.bail_key( + &key, + it.span, + "`yield*` result used other than by a const or a static read", + ); + } + } + } + } + walk_js::walk_yield_expression(self, it); + } + + fn visit_call_expression(&mut self, it: &CallExpression<'a>) { + let callee = strip(&it.callee); + // `Key.of(value)`. + if let Expression::StaticMemberExpression(member) = callee { + if member.property.name == "of" && self.shared.key_of(self.module, &member.object).is_some() { + self.classified.insert(strip(&member.object).span().start); + } + } + let api = self.shared.api_of(self.module, callee); + // A keyed lookup or `provideService` whose key arguments are all tracked + // keys reaches only those services: each keeps every method. Otherwise a + // lookup turns the pass off (`check_api`). + // A spread moves arguments at run time, so positions are unknown. + let spread = it.arguments.iter().any(|argument| matches!(argument, Argument::SpreadElement(_))); + if let Some(positions) = + api.filter(|_| !spread).and_then(|api| key_arguments(api, it.arguments.len())) + { + let keys: Option> = positions + .iter() + .map(|&position| { + let argument = it.arguments.get(position)?.as_expression()?; + let key = self.shared.key_of(self.module, argument)?; + Some((key.clone(), strip(argument).span().start)) + }) + .collect(); + if let (Some(api), Some(keys)) = (api.map(str::to_string), keys) { + for (key, start) in keys { + self.classified.insert(start); + self.bail_key(&key, it.span, &format!("service handed to `{api}`")); + } + self.handled_lookups.insert(it.callee.span().start); + } + } + if let Some(kind @ ("Layer.succeed" | "Layer.effect")) = api { + let key = it.arguments.first().and_then(Argument::as_expression).and_then(|first| { + self.shared.key_of(self.module, first).cloned().map(|key| (key, strip(first).span())) + }); + if let Some((key, key_span)) = key { + self.classified.insert(key_span.start); + if it.arguments.len() == 2 { + let container = self.container_from(it.span, self.path.len() - 1); + if let Some(value) = it.arguments[1].as_expression() { + self.provider(&key, kind, value, container); + } + } else if let Some(AstKind::CallExpression(outer)) = self.parent(0) { + if outer.callee.span() == it.span && outer.arguments.len() == 1 { + let container = self.container_from(outer.span, self.path.len() - 2); + if let Some(value) = outer.arguments[0].as_expression() { + self.provider(&key, kind, value, container); + } + } else { + self.bail_key(&key, it.span, "curried provider not applied"); + } + } else { + self.bail_key(&key, it.span, "curried provider not applied"); + } + } + } + if let Some("Context.Service" | "Context.Reference") = api { + if !self.shared.key_creations.contains(&(self.module, it.callee.span().start)) { + // The key string is on the outer call of the curried form `Context.Service<..>()("key")`. + let creation_call = match self.parent(0) { + Some(AstKind::CallExpression(outer)) if outer.callee.span() == it.span => outer, + _ => it, + }; + let trusted = self.trusted; + match key_string(creation_call) { + Some(key) => self.bail_key(&key, it.span, "service key created outside a declaration"), + // Effect's own modules create keys from constants or arguments. + None if trusted => {} + None => self.bail_global(it.span, "service key with a dynamic key string"), + } + } + } + walk_js::walk_call_expression(self, it); + } + + fn visit_object_expression(&mut self, it: &ObjectExpression<'a>) { + let Some(&site) = self.site_spans.get(&(self.module, it.span.start)) else { + walk_js::walk_object_expression(self, it); + return; + }; + let kind = AstKind::ObjectExpression(self.alloc(it)); + self.enter_node(kind); + for (index, property) in it.properties.iter().enumerate() { + match property { + ObjectPropertyKind::SpreadProperty(spread) => { + // Spread-in methods may read any property through `this`. + self.sites[site].top = true; + self.sites[site].props.push(Prop { + name: None, + span: spread.span, + prunable: false, + this_risk: false, + }); + self.visit_spread_element(spread); + } + ObjectPropertyKind::ObjectProperty(property) => { + let name = if property.computed { + None + } else { + property.key.static_name().and_then(|n| n.as_js_str().as_str().map(String::from)) + }; + let value = strip(&property.value); + let (pure, this_risk) = match value { + Expression::ArrowFunctionExpression(_) + | Expression::StringLiteral(_) + | Expression::NumericLiteral(_) + | Expression::BooleanLiteral(_) + | Expression::NullLiteral(_) => (true, false), + Expression::TemplateLiteral(template) => (template.expressions.is_empty(), false), + Expression::FunctionExpression(function) => (true, reads_this(function)), + Expression::Identifier(_) => { + // A binding known to hold a function that never reads `this`. Its + // read stays unless it cannot throw (temporal dead zone). + let resolved = self.shared.resolve_expr(self.module, value); + let this_free = matches!(resolved, Some(Resolved::Symbol(symbol)) if self.shared.this_free.contains(&symbol)); + (self.initialized_at(value, it.span.start), !this_free) + } + _ => (false, true), + }; + let prunable = pure + && property.kind == PropertyKind::Init + && name.as_deref().is_some_and(|name| name != "__proto__"); + // `__proto__: x` (non-computed, identifier or string key) sets the + // prototype, whose inherited methods may read any own property + // through `this`. Prototypes are not modelled, so keep the object. + let sets_prototype = name.as_deref() == Some("__proto__"); + if sets_prototype || property.kind != PropertyKind::Init { + self.sites[site].top = true; + } + // A value that may read `this` keeps every property only if it is + // kept itself: a removed property cannot be called. + self.sites[site].props.push(Prop { name, span: property.span, prunable, this_risk }); + self.guards.push(Guard::Property(site, index)); + self.visit_object_property(property); + self.guards.pop(); + } + } + } + self.leave_node(kind); + } + + fn visit_variable_declarator(&mut self, it: &VariableDeclarator<'a>) { + // A constructor-local `const f = () => ...` is a guard: reads inside it + // only count while something live references `f`. + let kind = match self.parent(0) { + Some(AstKind::VariableDeclaration(declaration)) => declaration.kind, + _ => VariableDeclarationKind::Var, + }; + let guard = match (&it.id, &it.init, kind) { + (BindingPattern::BindingIdentifier(id), Some(init), VariableDeclarationKind::Const) => { + let in_statement_list = + matches!(self.parent(1), Some(AstKind::FunctionBody(_) | AstKind::BlockStatement(_))); + let is_function = matches!( + strip(init), + Expression::ArrowFunctionExpression(_) | Expression::FunctionExpression(_) + ); + id.symbol_id.get().filter(|_| in_statement_list && is_function).map(|symbol| { + let symbol_ref: SymbolRef = (self.module, symbol).into(); + self.guard_bindings.push(GuardBinding { symbol: symbol_ref, declarator: it.span }); + symbol_ref + }) + } + _ => None, + }; + let kind = AstKind::VariableDeclarator(self.alloc(it)); + self.enter_node(kind); + self.visit_binding_pattern(&it.id); + if let Some(symbol) = guard { + self.guards.push(Guard::Binding(symbol)); + } + if let Some(init) = &it.init { + self.visit_expression(init); + } + if guard.is_some() { + self.guards.pop(); + } + self.leave_node(kind); + } + + fn visit_identifier_reference(&mut self, it: &IdentifierReference<'a>) { + self.record_reference(it); + let resolved = self.shared.resolve_ident(self.module, it); + if !self.trusted { + self.check_untrusted_reference(it, resolved); + self.check_host_reference(it); + if it.name == "Reflect" && it.reference_id.get().is_some() && resolved.is_none() { + self.check_reflect_value(it.span); + } + } + // The use expression of a key: the identifier, or `ns.Key` through any + // number of namespace hops. `use_depth` is the ancestor index of its parent. + let (key_symbol, use_span, use_depth) = match resolved { + Some(Resolved::Symbol(symbol)) => (Some(symbol), it.span, 0), + Some(Resolved::Namespace(target)) => match self.namespace_chain(it.span, target) { + NamespaceChain::Export { symbol, span, depth } => (Some(symbol), span, depth + 1), + NamespaceChain::Value(_) | NamespaceChain::Unresolved => (None, it.span, 0), + }, + None => (None, it.span, 0), + }; + if let Some(key) = key_symbol.and_then(|symbol| self.shared.keys.get(&symbol)).cloned() { + // Writes to a key's members can change what other keys resolve to. + let (member_written, static_read) = match self.parent(use_depth) { + Some(AstKind::StaticMemberExpression(member)) if member.object.span() == use_span => { + let written = self.is_write_target(use_depth + 1); + // A static member a class-form key declares itself; its body never + // mentions `this`, so the value reaches the key only by name. + let declared = key_symbol + .and_then(|symbol| self.shared.key_statics.get(&symbol)) + .is_some_and(|statics| statics.contains(member.property.name.as_str())); + (written, declared && !written) + } + _ => (false, false), + }; + if member_written { + self.bail_global(use_span, "service key member written"); + } + if static_read { + self.classified.insert(use_span.start); + } + self.classify_key_reference(&key, use_span, use_depth); + } + } + + fn visit_static_member_expression(&mut self, it: &StaticMemberExpression<'a>) { + if !self.trusted + && !matches!(self.shared.resolve_expr(self.module, &it.object), Some(Resolved::Namespace(_))) + { + self.check_member(&it.object, Some(it.property.name.as_str()), it.span); + // A1 assumes builtins are not modified; writes to their prototypes are + // cheap to see, so they turn the pass off instead. + if it.property.name == "prototype" + && self.is_global_value(&it.object) + && !self.read_in_place(it.span) + { + self.bail_global(it.span, "builtin prototype modified or used as a value"); + } + } + walk_js::walk_static_member_expression(self, it); + } + + fn visit_computed_member_expression(&mut self, it: &ComputedMemberExpression<'a>) { + if !self.trusted { + let name = self.shared.const_string(self.module, &it.expression); + self.check_member(&it.object, name.as_deref(), it.span); + } + walk_js::walk_computed_member_expression(self, it); + } + + fn visit_binding_property(&mut self, it: &BindingProperty<'a>) { + if !self.trusted { + self.check_property_key(&it.key, it.computed, it.span); + } + walk_js::walk_binding_property(self, it); + } + + fn visit_assignment_target_property_property( + &mut self, + it: &AssignmentTargetPropertyProperty<'a>, + ) { + if !self.trusted { + self.check_property_key(&it.name, it.computed, it.span); + } + walk_js::walk_assignment_target_property_property(self, it); + } + + fn visit_assignment_target_property_identifier( + &mut self, + it: &AssignmentTargetPropertyIdentifier<'a>, + ) { + if !self.trusted { + self.check_destructured_name(Some(it.binding.name.as_str()), it.span); + } + walk_js::walk_assignment_target_property_identifier(self, it); + } + + fn visit_import_expression(&mut self, it: &ImportExpression<'a>) { + if !self.trusted { + self.bail_global(it.span, "dynamic import"); + } + walk_js::walk_import_expression(self, it); + } +} + +struct Pruner<'s> { + properties: &'s FxHashSet, + declarators: &'s FxHashSet, +} + +impl<'a> VisitJsMut<'a> for Pruner<'_> { + fn visit_object_expression(&mut self, it: &mut ObjectExpression<'a>) { + it.properties.retain(|property| !self.properties.contains(&property.span().start)); + walk_js_mut::walk_object_expression(self, it); + } + + fn visit_statements(&mut self, it: &mut ArenaVec<'a, Statement<'a>>) { + for statement in it.iter_mut() { + if let Statement::VariableDeclaration(declaration) = statement { + declaration.declarations.retain(|d| !self.declarators.contains(&d.span.start)); + } + } + it.retain(|statement| { + !matches!(statement, Statement::VariableDeclaration(declaration) if declaration.declarations.is_empty()) + }); + walk_js_mut::walk_statements(self, it); + } +} + +impl LinkStage<'_> { + #[tracing::instrument(level = "debug", skip_all)] + #[expect(clippy::too_many_lines, reason = "one pass: collection, fixpoint and edits")] + pub(super) fn effect_service_shaking(&mut self) { + if !self.options.experimental.is_effect_service_shaking_enabled() { + return; + } + let mut report = Report::default(); + + // == shared facts + let mut namespaces = FxHashMap::default(); + let mut prefixes = vec![None; self.module_table.modules.len()]; + let mut resolved_exports = vec![FxHashMap::default(); self.module_table.modules.len()]; + for module in &self.module_table.modules { + if let Some(normal) = module.as_normal() { + namespaces.insert(self.symbols.canonical_ref_for(normal.namespace_object_ref), normal.idx); + prefixes[normal.idx.index()] = trusted_prefix(normal.id.as_str()); + resolved_exports[normal.idx.index()] = self.metas[normal.idx] + .resolved_exports + .iter() + .map(|(name, export)| (name.to_string(), export.symbol_ref)) + .collect(); + } + } + // External imports of untrusted code. Rolldown's own runtime imports + // `node:module` on Node, which is trusted like the effect package. + let mut externals: FxHashSet<&str> = FxHashSet::default(); + for module in &self.module_table.modules { + let Some(normal) = module.as_normal() else { continue }; + if prefixes[normal.idx.index()].is_some() || normal.idx == self.runtime.id() { + continue; + } + for record in &normal.import_records { + let Some(target) = record.resolved_module else { continue }; + if let Some(external) = self.module_table[target].as_external() { + externals.insert(external.name.as_str()); + } + } + } + for name in externals { + let builtin = NODE_BUILTINS.contains(&bare_module_name(name)) || name.starts_with("bun:"); + if !builtin { + report.global_bailouts.push(Bailout::global(format!("external import `{name}`"))); + } + } + for entry in &self.user_defined_entry_modules { + let Some(module) = self.module_table[*entry].as_normal() else { continue }; + if !module.named_exports.is_empty() || module.has_star_export() { + report.global_bailouts.push(Bailout::global(format!( + "entry module `{}` has exports, which code outside the bundle can call", + module.stable_id + ))); + } + } + // Imports of Node builtins that load code, followed through re-exports by + // canonical binding (A2). + let mut code_loaders: FxHashSet = FxHashSet::default(); + let mut capabilities: FxHashSet = FxHashSet::default(); + for module in &self.module_table.modules { + match module { + Module::Normal(normal) => { + for (symbol, named_import) in &normal.named_imports { + let Some(target) = normal.import_records[named_import.record_idx].resolved_module + else { + continue; + }; + let Some(external) = self.module_table[target].as_external() else { continue }; + let module_name = bare_module_name(external.name.as_str()); + let imported = match &named_import.imported { + Specifier::Star => None, + Specifier::Literal(name) => Some(name.as_str()), + }; + if CODE_LOADING_MODULES.contains(&module_name) + || imported.is_some_and(|name| CODE_LOADERS.contains(&name)) + { + code_loaders.insert(*symbol); + } + if module_name == "process" && imported.is_none_or(|name| name == "default") { + capabilities.insert(*symbol); + } + } + } + Module::External(external) => { + let module_name = bare_module_name(external.name.as_str()); + if CODE_LOADING_MODULES.contains(&module_name) { + code_loaders.insert(external.namespace_ref); + } + if module_name == "process" { + capabilities.insert(external.namespace_ref); + } + } + } + } + let mut api_names = FxHashMap::default(); + for exports in &resolved_exports { + for symbol in exports.values() { + let canonical = self.symbols.canonical_ref_for(*symbol); + if let Some(prefix) = &prefixes[canonical.owner.index()] { + let name = self.symbols.local_db(canonical.owner).scoping().symbol_name(canonical.symbol); + api_names.entry(canonical).or_insert_with(|| format!("{prefix}.{name}")); + } + } + } + let mut shared = Shared { + symbols: &self.symbols, + namespaces, + resolved_exports, + prefixes, + api_names, + keys: FxHashMap::default(), + key_creations: FxHashSet::default(), + this_free: FxHashSet::default(), + code_loaders, + capabilities, + const_strings: FxHashMap::default(), + key_statics: FxHashMap::default(), + builders: FxHashMap::default(), + }; + + // == pass A: keys + let normal_modules: Vec = + self.module_table.modules.iter().filter_map(|m| m.as_normal().map(|n| n.idx)).collect(); + let mut key_creations = vec![]; + let mut key_statics = vec![]; + let mut builders = vec![]; + let mut this_free = vec![]; + let mut const_strings: Vec<(SymbolRef, Vec)> = vec![]; + for module in &normal_modules { + let Some(ast) = self.ast_table[*module].as_ref() else { continue }; + ast.program.with_dependent(|_owner, dep| { + let mut collector = KeyCollector { + shared: &shared, + module: *module, + keys: vec![], + key_statics: vec![], + builders: vec![], + this_free: vec![], + const_strings: vec![], + depth: 0, + kind: VariableDeclarationKind::Var, + }; + collector.visit_program(&dep.program); + key_creations.extend(collector.keys.into_iter().map(|key| (*module, key))); + key_statics.extend(collector.key_statics); + builders.extend(collector.builders.into_iter().map(|builder| (*module, builder))); + this_free.extend(collector.this_free); + const_strings.extend(collector.const_strings); + }); + } + for symbol in this_free { + shared.this_free.insert(shared.symbols.canonical_ref_for(symbol)); + } + for (symbol, statics) in key_statics { + shared.key_statics.insert(shared.symbols.canonical_ref_for(symbol), statics); + } + // Only outside the trusted packages: A3 does not cover how Effect's own + // modules read Effect's own services. + for (module, (symbol, starts)) in builders { + if shared.prefixes[module.index()].is_none() { + shared.builders.insert(shared.symbols.canonical_ref_for(symbol), (module, starts)); + } + } + // `const` strings may be built from other `const` strings, in any module order. + let mut changed = true; + while changed { + changed = false; + for (symbol, parts) in &const_strings { + let symbol = shared.symbols.canonical_ref_for(*symbol); + if shared.const_strings.contains_key(&symbol) { + continue; + } + let value = parts.iter().try_fold(String::new(), |mut out, part| { + match part { + StringPart::Literal(literal) => out.push_str(literal), + StringPart::Binding(binding) => out.push_str(shared.const_strings.get(binding)?), + } + Some(out) + }); + if let Some(value) = value { + shared.const_strings.insert(symbol, value); + changed = true; + } + } + } + let mut dynamic_keys = vec![]; + for (module, (symbol, key, callee_start)) in key_creations { + shared.key_creations.insert((module, callee_start)); + match key { + KeyCreation::Literal(key) => { + shared.keys.insert(shared.symbols.canonical_ref_for(symbol), key); + } + KeyCreation::Dynamic => dynamic_keys.push(module), + } + } + for module in dynamic_keys { + if shared.prefixes[module.index()].is_none() { + report.global_bailouts.push(Bailout::at( + module, + 0, + "service key with a dynamic key string".to_string(), + )); + } + } + + // == pass B: uses + // Object literals returned by builder functions are visited as provider + // sites in their own module, before any provider that calls them is seen. + let mut sites: Vec = vec![]; + let mut site_spans: FxHashMap<(ModuleIdx, u32), usize> = FxHashMap::default(); + for (symbol, (module, starts)) in &shared.builders { + for start in starts { + site_spans.insert((*module, *start), sites.len()); + sites.push(Site { + module: *module, + keys: FxHashSet::default(), + props: vec![], + top: false, + bindings: vec![], + via: vec![*symbol], + }); + } + } + let mut accounted: FxHashSet<(ModuleIdx, u32)> = FxHashSet::default(); + let mut consumers = vec![]; + let mut providers = vec![]; + let mut guard_bindings = vec![]; + let mut refs: FxHashMap> = FxHashMap::default(); + let mut namespace_refs: Vec<(SymbolRef, RefInfo)> = vec![]; + let mut key_bailouts = vec![]; + for module in &normal_modules { + let Some(ast) = self.ast_table[*module].as_ref() else { continue }; + // Rolldown's own runtime module is trusted like the effect package. + let trusted = shared.prefixes[module.index()].is_some() || *module == self.runtime.id(); + ast.program.with_dependent(|_owner, dep| { + let mut collector = UseCollector { + shared: &shared, + module: *module, + trusted, + path: vec![], + guards: vec![], + top_stmt: 0, + refs: FxHashMap::default(), + namespace_refs: vec![], + classified: FxHashSet::default(), + site_spans: &mut site_spans, + sites: &mut sites, + module_consts: module_consts(&dep.program), + accounted: vec![], + handled_lookups: FxHashSet::default(), + constructors_in_progress: vec![], + constructor_cycle: false, + consumers: vec![], + providers: vec![], + guard_bindings: vec![], + global_bailouts: vec![], + key_bailouts: vec![], + }; + collector.visit_program(&dep.program); + accounted.extend(collector.accounted); + consumers.extend(collector.consumers.into_iter().map(|c| (*module, c))); + providers.extend(collector.providers.into_iter().map(|p| (*module, p))); + guard_bindings.extend(collector.guard_bindings); + report.global_bailouts.extend(collector.global_bailouts); + key_bailouts.extend(collector.key_bailouts); + refs.insert(*module, collector.refs); + namespace_refs.extend(collector.namespace_refs); + }); + } + + let mut demand: FxHashMap = FxHashMap::default(); + for (key, reason) in key_bailouts { + demand.entry(key.clone()).or_default().set_all(); + report.key_bailouts.push((key, reason)); + } + + // Containers of providers must stay inside the bundle. + // Uses of top-level bindings from other modules, indexed once. + let mut imported_refs: FxHashMap> = FxHashMap::default(); + for (module, module_refs) in &refs { + for info in module_refs.values() { + let Some(local) = info.root_symbol else { continue }; + let canonical = shared.symbols.canonical_ref_for((*module, local).into()); + if canonical.owner != *module { + imported_refs.entry(canonical).or_default().push(info); + } + } + } + for (export, info) in &namespace_refs { + imported_refs.entry(*export).or_default().push(info); + } + let references_of = |symbol: SymbolRef| -> Vec<&RefInfo> { + let scoping = shared.scoping(symbol.owner); + let module_refs = refs.get(&symbol.owner); + let mut out: Vec<&RefInfo> = scoping + .get_resolved_reference_ids(symbol.symbol) + .iter() + .filter_map(|id| module_refs.and_then(|r| r.get(id))) + .collect(); + if let Some(imported) = imported_refs.get(&symbol) { + out.extend(imported.iter().copied()); + } + out + }; + for (module, (key, container)) in &providers { + let mut pending = vec![*container]; + let mut seen = FxHashSet::default(); + while let Some(container) = pending.pop() { + match container { + Container::Terminal => {} + Container::Escape => { + demand.entry(key.clone()).or_default().set_all(); + report.key_bailouts.push((key.clone(), format!("Layer escapes (module {module:?})"))); + break; + } + Container::Binding(symbol) => { + if !seen.insert(symbol) { + continue; + } + for info in references_of(symbol) { + pending.push(info.container); + } + } + // Every use of a function returning the Layer must be a call. + Container::Factory(symbol) => { + if !seen.insert(symbol) { + continue; + } + for info in references_of(symbol) { + pending.push(info.call_result.unwrap_or(Container::Escape)); + } + } + } + } + } + + // An object returned through constructor or builder functions is a site + // only when it is provided and every reference to those functions is a + // call the pass followed into a provider: another caller would get the + // same pruned object. + for site in &mut sites { + let followed = |symbol: &SymbolRef| { + references_of(*symbol) + .iter() + .all(|info| accounted.contains(&(info.module, info.span.start))) + }; + if !site.via.is_empty() && (site.keys.is_empty() || !site.via.iter().all(followed)) { + site.top = true; + } + } + + // == liveness and demand fixpoint + let mut site_bindings_reads: Vec = vec![]; + for (index, site) in sites.iter().enumerate() { + let mut reads = vec![]; + let mut escaped = false; + for binding in &site.bindings { + for info in references_of(*binding) { + match &info.member { + Some((name, false)) if !INHERITED_MEMBERS.contains(&name.as_str()) => { + reads.push((name.clone(), info.chain.clone())); + } + _ => escaped = true, + } + } + } + site_bindings_reads.push((index, reads, escaped)); + } + let mut consumer_reads: Vec<(String, String, Vec)> = vec![]; + for (module, consumer) in &consumers { + match &consumer.kind { + ConsumerKind::Names(names) => { + for name in names { + consumer_reads.push((consumer.key.clone(), name.clone(), consumer.chain.clone())); + } + } + ConsumerKind::Binding(symbol) => { + for info in references_of(*symbol) { + match &info.member { + Some((name, false)) if !INHERITED_MEMBERS.contains(&name.as_str()) => { + let mut chain = consumer.chain.clone(); + chain.extend(info.chain.iter().copied()); + consumer_reads.push((consumer.key.clone(), name.clone(), chain)); + } + Some((name, true)) => { + demand.entry(consumer.key.clone()).or_default().set_all(); + report.key_bailouts.push(( + consumer.key.clone(), + format!("service member `{name}` written (module {module:?})"), + )); + } + _ => { + demand.entry(consumer.key.clone()).or_default().set_all(); + report.key_bailouts.push(( + consumer.key.clone(), + format!( + "service value used other than by static member reads (module {module:?} at {})", + info.span.start + ), + )); + } + } + } + } + } + } + let binding_refs: Vec<(SymbolRef, Vec>)> = guard_bindings + .iter() + .map(|binding| { + ( + binding.symbol, + references_of(binding.symbol).iter().map(|info| info.chain.clone()).collect(), + ) + }) + .collect(); + + let mut site_demand: Vec = sites.iter().map(|_| Demand::default()).collect(); + let mut live_bindings: FxHashSet = FxHashSet::default(); + let retained = |site_demand: &Vec, site: usize, prop: usize| -> bool { + let s = &sites[site]; + let Some(p) = s.props.get(prop) else { return true }; + s.top || !p.prunable || p.name.as_deref().is_none_or(|name| site_demand[site].has(name)) + }; + let live = + |site_demand: &Vec, live_bindings: &FxHashSet, chain: &[Guard]| { + chain.iter().all(|guard| match guard { + Guard::Property(site, prop) => retained(site_demand, *site, *prop), + Guard::Binding(symbol) => live_bindings.contains(symbol), + }) + }; + loop { + let mut changed = false; + for (key, name, chain) in &consumer_reads { + if live(&site_demand, &live_bindings, chain) { + changed |= demand.entry(key.clone()).or_default().add(name); + } + } + for (index, site) in sites.iter().enumerate() { + for key in &site.keys { + if let Some(key_demand) = demand.get(key) { + changed |= site_demand[index].add_all(key_demand); + } + } + } + for (index, reads, escaped) in &site_bindings_reads { + if *escaped { + changed |= site_demand[*index].set_all(); + } + for (name, chain) in reads { + if live(&site_demand, &live_bindings, chain) { + changed |= site_demand[*index].add(name); + } + } + } + // A kept property that may read `this` keeps every property. + for (index, site) in sites.iter().enumerate() { + for (prop_index, prop) in site.props.iter().enumerate() { + if prop.this_risk && retained(&site_demand, index, prop_index) { + changed |= site_demand[index].set_all(); + } + } + } + for (symbol, chains) in &binding_refs { + if !live_bindings.contains(symbol) + && chains.iter().any(|chain| live(&site_demand, &live_bindings, chain)) + { + live_bindings.insert(*symbol); + changed = true; + } + } + if !changed { + break; + } + } + + // == edits + let mut removed_properties: FxHashMap> = FxHashMap::default(); + let mut removed_spans: FxHashMap> = FxHashMap::default(); + let mut removed_declarators: FxHashMap> = FxHashMap::default(); + if report.global_bailouts.is_empty() { + for (index, site) in sites.iter().enumerate() { + for (prop_index, prop) in site.props.iter().enumerate() { + if retained(&site_demand, index, prop_index) { + continue; + } + removed_properties.entry(site.module).or_default().insert(prop.span.start); + removed_spans.entry(site.module).or_default().push(prop.span); + report.removed.push(format!( + "{}: property `{}`", + self.module_table[site.module].stable_id(), + prop.name.as_deref().unwrap_or_default() + )); + } + } + for binding in &guard_bindings { + if live_bindings.contains(&binding.symbol) { + continue; + } + let module = binding.symbol.owner; + removed_declarators.entry(module).or_default().insert(binding.declarator.start); + removed_spans.entry(module).or_default().push(binding.declarator); + report.removed.push(format!( + "{}: local `{}`", + self.module_table[module].stable_id(), + shared.scoping(module).symbol_name(binding.symbol.symbol) + )); + } + } + + // Statement references that only occurred inside removed code. + let mut stmt_updates: Vec<(ModuleIdx, usize, FxHashSet, Vec)> = vec![]; + for (module, spans) in &removed_spans { + let within = |span: Span| spans.iter().any(|removed| removed.contains_inclusive(span)); + let mut counts: FxHashMap<(usize, SymbolId), (usize, usize)> = FxHashMap::default(); + for info in refs.get(module).into_iter().flat_map(|r| r.values()) { + let Some(symbol) = info.root_symbol else { continue }; + let entry = counts.entry((info.top_stmt, symbol)).or_default(); + entry.0 += 1; + if within(info.span) { + entry.1 += 1; + } + } + let mut by_stmt: FxHashMap> = FxHashMap::default(); + for ((stmt, symbol), (total, removed)) in counts { + if removed > 0 && removed == total { + by_stmt.entry(stmt).or_default().insert(symbol); + } + } + let touched: FxHashSet = refs + .get(module) + .into_iter() + .flat_map(|r| r.values()) + .filter(|info| within(info.span)) + .map(|info| info.top_stmt) + .collect(); + for stmt in touched { + stmt_updates.push(( + *module, + stmt, + by_stmt.remove(&stmt).unwrap_or_default(), + spans.clone(), + )); + } + } + drop(shared); + + let edited: FxHashSet = + removed_properties.keys().chain(removed_declarators.keys()).copied().collect(); + let empty = FxHashSet::default(); + for module in edited { + let properties = removed_properties.get(&module).unwrap_or(&empty); + let declarators = removed_declarators.get(&module).unwrap_or(&empty); + if let Some(ast) = self.ast_table[module].as_mut() { + ast.program.with_mut(|fields| { + Pruner { properties, declarators }.visit_program(fields.program); + }); + } + } + for (module, stmt, symbols, spans) in stmt_updates { + if stmt >= self.stmt_infos[module].len() { + continue; + } + let stmt_info = self.stmt_infos[module].get_mut(StmtInfoIdx::new(stmt)); + stmt_info.referenced_symbols.retain(|reference| match reference { + SymbolOrMemberExprRef::Symbol(symbol) => { + !(symbol.owner == module && symbols.contains(&symbol.symbol)) + } + SymbolOrMemberExprRef::MemberExpr(member) => { + !spans.iter().any(|removed| removed.contains_inclusive(member.span)) + } + }); + } + + self.report_effect_service_bailouts(&report.global_bailouts); + tracing::debug!(?report, "effect service shaking"); + #[expect(clippy::print_stderr, reason = "opt-in report for measuring the experimental pass")] + if std::env::var_os("ROLLDOWN_EFFECT_SERVICE_SHAKING_REPORT").is_some() { + eprintln!("[effect-service-shaking] global bailouts: {:#?}", report.global_bailouts); + eprintln!("[effect-service-shaking] key bailouts: {:#?}", report.key_bailouts); + eprintln!("[effect-service-shaking] removed: {:#?}", report.removed); + let mut demand: Vec<_> = demand + .iter() + .map(|(key, d)| { + let mut names: Vec<_> = d.names.iter().cloned().collect(); + names.sort(); + (key.clone(), if d.all { "all".to_string() } else { names.join(",") }) + }) + .collect(); + demand.sort(); + eprintln!("[effect-service-shaking] demand: {demand:#?}"); + } + } + + /// Every reason the pass was turned off, one `EFFECT_SERVICE_SHAKING` warning + /// per site, with the site's 1-based line and column. + fn report_effect_service_bailouts(&mut self, bailouts: &[Bailout]) { + let mut reported: FxHashSet> = FxHashSet::default(); + for bailout in bailouts { + if !reported.insert(bailout.site) { + continue; + } + let site = bailout + .site + .and_then(|(module, offset)| self.module_table[module].as_normal().map(|n| (n, offset))); + let (id, position) = match site { + Some((normal, offset)) => { + let before = normal.source.get(..offset as usize).unwrap_or_default(); + let line = before.matches('\n').count() + 1; + let column = before.len() - before.rfind('\n').map_or(0, |newline| newline + 1) + 1; + (Some(normal.id.to_string()), Some((line, column))) + } + None => (None, None), + }; + self.diagnostics.push( + BuildDiagnostic::effect_service_shaking(id, "bailout", bailout.reason.clone(), position) + .with_severity_warning(), + ); + } + } +} diff --git a/crates/rolldown/src/stages/link_stage/mod.rs b/crates/rolldown/src/stages/link_stage/mod.rs index 0bc586b3bea9..159daf652756 100644 --- a/crates/rolldown/src/stages/link_stage/mod.rs +++ b/crates/rolldown/src/stages/link_stage/mod.rs @@ -37,6 +37,7 @@ mod compute_tla; mod create_exports_for_ecma_modules; mod cross_module_optimization; mod determine_module_exports_kind; +mod effect_service_shaking; mod generate_lazy_export; mod patch_module_dependencies; mod reference_needed_symbols; @@ -275,6 +276,7 @@ impl<'a> LinkStage<'a> { // The passes above only relax statement flags. Module verdicts must follow before // `reference_needed_symbols` derives import flags from them. self.recompute_analyzed_side_effects(); + self.effect_service_shaking(); self.reference_needed_symbols(); self.include_statements(&unreachable_import_expression_node_ids); self.patch_module_dependencies(); diff --git a/crates/rolldown/tests/rolldown/topics/effect_service_bailouts/mod.rs b/crates/rolldown/tests/rolldown/topics/effect_service_bailouts/mod.rs new file mode 100644 index 000000000000..d6acdbf7274f --- /dev/null +++ b/crates/rolldown/tests/rolldown/topics/effect_service_bailouts/mod.rs @@ -0,0 +1,141 @@ +//! Where `experimental.effectServiceShaking` turns itself off, checked per site. +//! +//! Every reason the pass is turned off is an `EFFECT_SERVICE_SHAKING` warning: +//! `id()` is the module of the site, and the message contains `[bailout]` and +//! `at :`, 1-based, not followed by another digit. These tests check +//! that a bailout is present at the expected site, not that it is the only one. +//! +//! The fixtures in `tree_shaking/effect_service_real` check behaviour and that no +//! method is removed separately. + +use rolldown::{Bundler, BundlerOptions, ExperimentalOptions, InputItem, Platform}; + +const FIXTURES: &str = + concat!(env!("CARGO_MANIFEST_DIR"), "/tests/rolldown/tree_shaking/effect_service_real"); + +type Reason = (Option, String); + +/// The `EFFECT_SERVICE_SHAKING` warnings of bundling `/main.js`. +async fn reasons(dir: &str) -> Vec { + let mut bundler = Bundler::new(BundlerOptions { + input: Some(vec![InputItem { + name: Some("main".to_string()), + import: "./main.js".to_string(), + }]), + cwd: Some(format!("{FIXTURES}/{dir}").into()), + platform: Some(Platform::Node), + experimental: Some(ExperimentalOptions { + effect_service_shaking: Some(true), + ..Default::default() + }), + ..Default::default() + }) + .expect("failed to create bundler"); + let output = bundler.generate().await.expect("build should succeed"); + output + .warnings + .iter() + .filter(|warning| warning.kind().to_string() == "EFFECT_SERVICE_SHAKING") + .map(|warning| (warning.id(), warning.to_string())) + .collect() +} + +/// `line:col`, 1-based, of the only occurrence of `needle` in `/main.js`. +fn position(dir: &str, needle: &str) -> String { + let source = std::fs::read_to_string(format!("{FIXTURES}/{dir}/main.js")).unwrap(); + let mut matches = source.match_indices(needle); + let (offset, _) = matches.next().unwrap_or_else(|| panic!("`{needle}` not in {dir}/main.js")); + assert!(matches.next().is_none(), "`{needle}` occurs more than once in {dir}/main.js"); + let before = &source[..offset]; + let line = before.matches('\n').count() + 1; + let column = before.len() - before.rfind('\n').map_or(0, |newline| newline + 1) + 1; + format!("{line}:{column}") +} + +/// Whether `message` reports `at ` with no further digit after it. +fn reports_site(message: &str, site: &str) -> bool { + let needle = format!("at {site}"); + message + .match_indices(&needle) + .any(|(offset, _)| !message[offset + needle.len()..].starts_with(|c: char| c.is_ascii_digit())) +} + +/// `None` if bundling `/main.js` reports a bailout at `needle`, else why not. +async fn missing_bailout(dir: &str, needle: &str) -> Option { + let reasons = reasons(dir).await; + let site = position(dir, needle); + let found = reasons.iter().any(|(id, message)| { + id.as_deref().is_some_and(|id| id.ends_with(&format!("{dir}/main.js"))) + && message.contains("[bailout]") + && reports_site(message, &site) + }); + (!found) + .then(|| format!("expected a bailout at {dir}/main.js:{site} (`{needle}`), got: {reasons:#?}")) +} + +async fn assert_bailout(dir: &str, needle: &str) { + if let Some(error) = missing_bailout(dir, needle).await { + panic!("{error}"); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn update_service_scoped_is_a_keyed_lookup() { + assert_bailout("lookup_update_service_scoped", "Effect.updateServiceScoped(").await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn get_or_undefined_unsafe_works_on_key_strings() { + assert_bailout("string_key_get_or_undefined_unsafe", "Context.getOrUndefinedUnsafe(").await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn make_unsafe_works_on_key_strings() { + assert_bailout("string_key_make_unsafe", "Context.makeUnsafe(").await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn reexported_loader_loads_code() { + assert_bailout("loader_reexport", "compile(\"return 1\")").await; +} + +#[tokio::test(flavor = "multi_thread")] +async fn computed_host_access_may_load_code() { + assert_bailout("loader_computed_access", "process[").await; +} + +/// A constant computed name for the Function constructor is a code loader. +/// Names known only at run time are outside the contract (A2) and not checked. +#[tokio::test(flavor = "multi_thread")] +async fn constant_function_constructor_name_loads_code() { + let mut errors = Vec::new(); + for (dir, needle) in [ + ("loader_function_constructor_global", "globalThis.Object["), + ("loader_function_constructor_arrow", "(() => 0)["), + ] { + errors.extend(missing_bailout(dir, needle).await); + } + assert!(errors.is_empty(), "{}", errors.join("\n")); +} + +#[tokio::test(flavor = "multi_thread")] +async fn reflect_get_with_a_loader_name_loads_code() { + assert_bailout("loader_reflect_get", "Reflect.get(").await; +} + +/// `Reflect.get` with a literal loader name, through `globalThis.Reflect`, an +/// alias of it, or a spread before the key. Rolldown inlines the +/// `const reflect = globalThis.Reflect` alias before the pass runs, so that +/// path reports at the inlined `reflect.get(` call. +#[tokio::test(flavor = "multi_thread")] +async fn qualified_or_spread_reflect_get_loads_code() { + let mut errors = Vec::new(); + for (dir, needle) in [ + ("loader_reflect_get_global", "globalThis.Reflect.get("), + ("loader_reflect_get_global", "reflect.get("), + ("loader_reflect_get_spread", "Reflect.get(...[]"), + ] { + errors.extend(missing_bailout(dir, needle).await); + } + assert!(errors.is_empty(), "{}", errors.join("\n")); +} diff --git a/crates/rolldown/tests/rolldown/topics/mod.rs b/crates/rolldown/tests/rolldown/topics/mod.rs index 9d4b0627c1bf..fd0d19c05729 100644 --- a/crates/rolldown/tests/rolldown/topics/mod.rs +++ b/crates/rolldown/tests/rolldown/topics/mod.rs @@ -1,3 +1,4 @@ mod deconflict; +mod effect_service_bailouts; mod hmr; mod runtime; diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/distilled_stripe/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/distilled_stripe/_config.json new file mode 100644 index 000000000000..8f5a73a392b0 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/distilled_stripe/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Measurement fixture: the real @distilled.cloud/stripe generated client. Its core compiles operation specs with `Function`, so the pass turns itself off (A2). Not snapshotted, and outside the effect_service filter.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "snapshot": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/distilled_stripe/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/distilled_stripe/_test.mjs new file mode 100644 index 000000000000..d02ba79f731c --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/distilled_stripe/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Operations are separate module-level exports, so Rolldown's own tree shaking +// keeps only the one used, with or without the service pass. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +assert.match(code, /`CreateCustomerRequest`/, "CreateCustomer should be kept") +for (const name of ["CreateAccountRequest", "CreateInvoiceRequest"]) { + assert.doesNotMatch(code, new RegExp(`\`${name}\``), `${name} should be removed`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/distilled_stripe/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/distilled_stripe/main.js new file mode 100644 index 000000000000..534df25d9cb3 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/distilled_stripe/main.js @@ -0,0 +1,36 @@ +import assert from "node:assert" +import * as Stripe from "@distilled.cloud/stripe" +import { CreateCustomer } from "@distilled.cloud/stripe/stripe" +import * as Effect from "effect/Effect" +import * as HttpClient from "effect/http/HttpClient" +import * as HttpClientResponse from "effect/http/HttpClientResponse" +import * as Layer from "effect/Layer" +import * as Redacted from "effect/Redacted" + +// The generated Stripe client from @distilled.cloud/stripe 1.0.0-rc.18, with one +// operation called against a deterministic mock transport. +const requests = [] + +const MockHttpClient = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => { + requests.push(`${request.method} ${request.url}`) + return Effect.succeed(HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify({ id: "cus_test", object: "customer", email: "ops@example.com" }), { + status: 200, + headers: { "content-type": "application/json" } + }) + )) + }) +) + +const Live = Layer.mergeAll( + MockHttpClient, + Stripe.credentials({ apiKey: Redacted.make("sk_test"), apiBaseUrl: "https://mock.invalid" }), + Stripe.StripeProtocol +) + +const customer = await Effect.runPromise(CreateCustomer({ email: "ops@example.com" }).pipe(Effect.provide(Live))) +assert.deepStrictEqual(customer, { id: "cus_test", object: "customer", email: "ops@example.com" }) +assert.deepStrictEqual(requests, ["POST https://mock.invalid/v1/customers"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/openai/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/openai/_config.json new file mode 100644 index 000000000000..d4a0d76fe489 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/openai/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Measurement fixture: the real @effect/ai-openai generated client. The bundle is about 2 MB, so it is not snapshotted, and it sits outside the effect_service filter to keep that 10-second CI step within budget.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "snapshot": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/openai/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/openai/_test.mjs new file mode 100644 index 000000000000..c23d26cffaa5 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/openai/_test.mjs @@ -0,0 +1,16 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Only `retrieveModel` is called: it and its response schema stay, while an +// unused method and the schema only it needs are removed. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["retrieveModel", "RetrieveModel200"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} +for (const name of ["listAssistants", "ListAssistants200"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/openai/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/openai/main.js new file mode 100644 index 000000000000..3cfa421cae5e --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_generated_client/openai/main.js @@ -0,0 +1,37 @@ +import assert from "node:assert" +import * as Effect from "effect/Effect" +import * as HttpClient from "effect/http/HttpClient" +import * as HttpClientResponse from "effect/http/HttpClientResponse" +import * as Layer from "effect/Layer" +import * as OpenAiClientGenerated from "@effect/ai-openai/OpenAiClientGenerated" + +// The generated OpenAI client from @effect/ai-openai, reached through its +// service, with one method called against a deterministic mock transport. +const requests = [] + +const MockHttpClient = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => { + requests.push(`${request.method} ${request.url}`) + return Effect.succeed(HttpClientResponse.fromWeb( + request, + new Response( + JSON.stringify({ id: "gpt-test", object: "model", created: 1700000000, owned_by: "test" }), + { status: 200, headers: { "content-type": "application/json" } } + ) + )) + }) +) + +const ClientLayer = OpenAiClientGenerated.layer({ apiUrl: "https://mock.invalid/v1" }).pipe( + Layer.provide(MockHttpClient) +) + +const program = Effect.gen(function* () { + const client = yield* OpenAiClientGenerated.OpenAiClientGenerated + return yield* client.retrieveModel("gpt-test", undefined) +}) + +const model = await Effect.runPromise(Effect.provide(program, ClientLayer)) +assert.deepStrictEqual(model, { id: "gpt-test", object: "model", created: 1700000000, owned_by: "test" }) +assert.deepStrictEqual(requests, ["GET https://mock.invalid/v1/models/gpt-test"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/_test.mjs new file mode 100644 index 000000000000..ccbb9f352728 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of []) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["writeHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/artifacts.snap new file mode 100644 index 000000000000..67a652799c62 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/artifacts.snap @@ -0,0 +1,88 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] entry module `main.js` has exports, which code outside the bundle can call + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const map = (self, f) => make(async (context, scope) => f(await self.run(context, scope))); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +// main.js +const Store = Service("test/Store"); +const readHelper = () => "read"; +const writeHelper = () => "write"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + const writeOne = () => writeHelper(); + return Store.of({ + readOne, + writeOne + }); +})); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +assert.strictEqual(await runPromise(provide(program, StoreLayer)), "read"); +const run = (input) => runPromise(provide(map(program, (value) => `${value}${input}`), StoreLayer)); +export { run }; + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/main.js new file mode 100644 index 000000000000..cea3ea98fd7f --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_entry_export/main.js @@ -0,0 +1,30 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The base case, but the entry module exports a function. Whoever imports the +// bundle can call it with values whose getters run inside the program, so +// nothing may be removed. +const Store = Context.Service("test/Store") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + return store.readOne() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), "read") + +export const run = (input) => Effect.runPromise(Effect.provide(Effect.map(program, (value) => `${value}${input}`), StoreLayer)) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/_test.mjs new file mode 100644 index 000000000000..6c9e309dc627 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of []) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["unusedA", "unusedB", "unusedC", "unusedD", "unusedE", "unusedF"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/artifacts.snap new file mode 100644 index 000000000000..dc098e8ad1e3 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/artifacts.snap @@ -0,0 +1,176 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/A` used in CallExpression at 44:12 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/A` used in CallExpression at 55:31 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/B` used in CallExpression at 45:12 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/C` used in CallExpression at 46:12 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/C` used in StaticMemberExpression at 57:20 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/D` used in CallExpression at 47:12 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/E` used in CallExpression at 48:12 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const succeed = (value) => make(async () => value); +const map = (self, f) => make(async (context, scope) => f(await self.run(context, scope))); +const flatMap = (self, f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const context = () => make(async (context) => context); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +const get = (context, service) => context.get(service.key); +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +const mergeAll = (...layers) => ({ build: async (context, scope) => { + let merged = new Map(context); + for (const layer of layers) merged = new Map([...merged, ...await layer.build(context, scope)]); + return merged; +} }); +// main.js +const A = Service("test/A"); +const B = Service("test/B"); +const C = Service("test/C"); +const D = Service("test/D"); +const E = Service("test/E"); +const F = Service("test/F"); +const unusedA = () => "unusedA"; +const unusedB = () => "unusedB"; +const unusedC = () => "unusedC"; +const unusedD = () => "unusedD"; +const unusedE = () => "unusedE"; +const unusedF = () => "unusedF"; +const provider = (key, unused) => effect(key, gen(function* () { + const used = () => "used"; + return key.of({ + used, + unused + }); +})); +const FLayer = effect(F, gen(function* () { + return F.of({ + used() { + return this.unused(); + }, + unused: () => unusedF() + }); +})); +const layer = mergeAll(provider(A, () => unusedA()), provider(B, () => unusedB()), provider(C, () => unusedC()), provider(D, () => unusedD()), provider(E, () => unusedE()), FLayer); +const describe = (service) => Object.keys(service).join(","); +const program = gen(function* () { + const a = yield* map(A, (a) => a.used()); + const b = yield* flatMap(context(), (context) => succeed(get(context, B).used())); + const c = yield* C.use((c) => succeed(c.used())); + const d = describe(yield* D); + const e = yield* E; + const name = ["un", "used"].join(""); + const f = yield* F; + return [ + a, + b, + c, + d, + e[name](), + f.used() + ]; +}); +assert.deepStrictEqual(await runPromise(provide(program, layer)), [ + "used", + "used", + "used", + "used,unused", + "unusedE", + "unusedF" +]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/main.js new file mode 100644 index 000000000000..d02560039c86 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/bailout_unsupported_access/main.js @@ -0,0 +1,72 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Each service is provided in the base-case shape but consumed through a path +// outside the base case, so every one of them keeps `unused`. +const A = Context.Service("test/A") // combinator: Effect.map(A, f) +const B = Context.Service("test/B") // direct Context access +const C = Context.Service("test/C") // Key.use +const D = Context.Service("test/D") // the service escapes to a function +const E = Context.Service("test/E") // computed member access +const F = Context.Service("test/F") // a method reads `this` + +const unusedA = () => "unusedA" +const unusedB = () => "unusedB" +const unusedC = () => "unusedC" +const unusedD = () => "unusedD" +const unusedE = () => "unusedE" +const unusedF = () => "unusedF" + +const provider = (key, unused) => + Layer.effect( + key, + Effect.gen(function* () { + const used = () => "used" + return key.of({ used, unused }) + }) + ) + +const FLayer = Layer.effect( + F, + Effect.gen(function* () { + return F.of({ + used() { + return this.unused() + }, + unused: () => unusedF() + }) + }) +) + +const layer = Layer.mergeAll( + provider(A, () => unusedA()), + provider(B, () => unusedB()), + provider(C, () => unusedC()), + provider(D, () => unusedD()), + provider(E, () => unusedE()), + FLayer +) + +const describe = (service) => Object.keys(service).join(",") + +const program = Effect.gen(function* () { + const a = yield* Effect.map(A, (a) => a.used()) + const b = yield* Effect.flatMap(Effect.context(), (context) => Effect.succeed(Context.get(context, B).used())) + const c = yield* C.use((c) => Effect.succeed(c.used())) + const d = describe(yield* D) + const e = yield* E + const name = ["un", "used"].join("") + const f = yield* F + return [a, b, c, d, e[name](), f.used()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, layer)), [ + "used", + "used", + "used", + "used,unused", + "unusedE", + "unusedF" +]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/class_receiver/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/class_receiver/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/class_receiver/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/class_receiver/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/class_receiver/artifacts.snap new file mode 100644 index 000000000000..1158a31ca763 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/class_receiver/artifacts.snap @@ -0,0 +1,77 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +// main.js +const K = Service("test/ClassReceiver"); +const layer = effect(K, gen(function* () { + return { + read: function() { + const C = class extends this.unused() {}; + return new C().value; + }, + unused: () => class { + value = 2; + } + }; +})); +const program = gen(function* () { + return (yield* K).read(); +}); +assert.strictEqual(await runPromise(provide(program, layer)), 2); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/class_receiver/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/class_receiver/main.js new file mode 100644 index 000000000000..6687ccc37da4 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/class_receiver/main.js @@ -0,0 +1,30 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A class heritage expression runs with the method's receiver, so `read` +// reads `this.unused` even though it is inside a class. +const K = Context.Service("test/ClassReceiver") + +const layer = Layer.effect( + K, + Effect.gen(function* () { + return { + read: function () { + const C = class extends this.unused() {} + return new C().value + }, + unused: () => + class { + value = 2 + } + } + }) +) + +const program = Effect.gen(function* () { + return (yield* K).read() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, layer)), 2) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/_test.mjs new file mode 100644 index 000000000000..e3d1caae4ea6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["readHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/artifacts.snap new file mode 100644 index 000000000000..a9fb34d57dae --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/artifacts.snap @@ -0,0 +1,71 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +// main.js +const Store = Service("test/Store"); +const readHelper = () => "read"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + return Store.of({ readOne }); +})); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +assert.strictEqual(await runPromise(provide(program, StoreLayer)), "read"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/main.js new file mode 100644 index 000000000000..c98af3c18d71 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/constructor_local_methods/main.js @@ -0,0 +1,27 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Base case: a provider built by `Layer.effect` + `Effect.gen` whose methods +// are constructor-local consts, consumed with `yield*`. Only `readOne` is read. +const Store = Context.Service("test/Store") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + return store.readOne() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), "read") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/explicit_prototype/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/explicit_prototype/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/explicit_prototype/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/explicit_prototype/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/explicit_prototype/artifacts.snap new file mode 100644 index 000000000000..0e1182b10445 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/explicit_prototype/artifacts.snap @@ -0,0 +1,76 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +// main.js +const K = Service("test/ExplicitPrototype"); +const proto = () => 0; +proto.read = function() { + return this.unused(); +}; +const layer = effect(K, gen(function* () { + return { + __proto__: proto, + unused: () => 2 + }; +})); +const program = gen(function* () { + return (yield* K).read(); +}); +assert.strictEqual(await runPromise(provide(program, layer)), 2); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/explicit_prototype/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/explicit_prototype/main.js new file mode 100644 index 000000000000..0d8536ad10a3 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/explicit_prototype/main.js @@ -0,0 +1,26 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The provider sets its prototype explicitly. `read` is inherited from it and +// reads `this.unused` from the service object. +const K = Context.Service("test/ExplicitPrototype") + +const proto = () => 0 +proto.read = function () { + return this.unused() +} + +const layer = Layer.effect( + K, + Effect.gen(function* () { + return { __proto__: proto, unused: () => 2 } + }) +) + +const program = Effect.gen(function* () { + return (yield* K).read() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, layer)), 2) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_constructor_alias/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_constructor_alias/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_constructor_alias/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_constructor_alias/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_constructor_alias/artifacts.snap new file mode 100644 index 000000000000..f8b702d6db8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_constructor_alias/artifacts.snap @@ -0,0 +1,80 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Context.Service` used other than to declare a service key at 8:17 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +const Hidden = Service("test/Aliased"); +const layer = effect(Service("test/Aliased"), gen(function* () { + return { + read: () => 1, + unused: () => 2 + }; +})); +const program = gen(function* () { + return (yield* Hidden).read(); +}); +assert.strictEqual(await runPromise(provide(program, layer)), 1); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_constructor_alias/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_constructor_alias/main.js new file mode 100644 index 000000000000..1f3fb8da7385 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_constructor_alias/main.js @@ -0,0 +1,23 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Keys created through an alias of `Context.Service` share the key string of +// the provided service, so yielding them finds it. +const factory = Context.Service +const Hidden = factory("test/Aliased") +const K = Context.Service("test/Aliased") + +const layer = Layer.effect( + K, + Effect.gen(function* () { + return { read: () => 1, unused: () => 2 } + }) +) + +const program = Effect.gen(function* () { + return (yield* Hidden).read() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, layer)), 1) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_retarget/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_retarget/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_retarget/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_retarget/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_retarget/artifacts.snap new file mode 100644 index 000000000000..1f4caf82545f --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_retarget/artifacts.snap @@ -0,0 +1,102 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/Computed` used in ComputedMemberExpression at 17:1 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/Helper` used in CallExpression at 16:10 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function succeed(service, value) { + if (arguments.length === 1) return (value) => succeed(service, value); + return { build: async (context) => new Map(context).set(service.key, value) }; +} +const mergeAll = (...layers) => ({ build: async (context, scope) => { + let merged = new Map(context); + for (const layer of layers) merged = new Map([...merged, ...await layer.build(context, scope)]); + return merged; +} }); +// main.js +const Helper = Service("test/Helper"); +const Computed = Service("test/Computed"); +const HelperTarget = Service("test/HelperTarget"); +const ComputedTarget = Service("test/ComputedTarget"); +function retarget(key, to) { + key.key = to; +} +retarget(Helper, "test/HelperTarget"); +Computed[["key"].join("")] = "test/ComputedTarget"; +const layer = mergeAll(succeed(HelperTarget, { + read: () => 1, + unused: () => 2 +}), succeed(ComputedTarget, { + read: () => 3, + unused: () => 4 +})); +const program = gen(function* () { + return [(yield* Helper).read(), (yield* Computed).read()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, layer)), [1, 3]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_retarget/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_retarget/main.js new file mode 100644 index 000000000000..e6df1734e721 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/key_retarget/main.js @@ -0,0 +1,28 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Keys retargeted by opaque code: after this, yielding Helper or Computed +// finds the services provided for the "other" keys. +const Helper = Context.Service("test/Helper") +const Computed = Context.Service("test/Computed") +const HelperTarget = Context.Service("test/HelperTarget") +const ComputedTarget = Context.Service("test/ComputedTarget") + +function retarget(key, to) { + key.key = to +} +retarget(Helper, "test/HelperTarget") +Computed[["key"].join("")] = "test/ComputedTarget" + +const layer = Layer.mergeAll( + Layer.succeed(HelperTarget, { read: () => 1, unused: () => 2 }), + Layer.succeed(ComputedTarget, { read: () => 3, unused: () => 4 }) +) + +const program = Effect.gen(function* () { + return [(yield* Helper).read(), (yield* Computed).read()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, layer)), [1, 3]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/_test.mjs new file mode 100644 index 000000000000..158dfb434e40 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "dependencyWrite", "auditRecord"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["dependencyPrepare", "dependencyDescribe", "makeCache"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/artifacts.snap new file mode 100644 index 000000000000..8a7768f9880c --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/artifacts.snap @@ -0,0 +1,124 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const sync = (evaluate) => make(async () => evaluate()); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const acquireRelease = (acquire, release) => make(async (context, scope) => { + const value = await acquire.run(context, scope); + scope.push(() => release(value).run(context, scope)); + return value; +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide$1 = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +function succeed(service, value) { + if (arguments.length === 1) return (value) => succeed(service, value); + return { build: async (context) => new Map(context).set(service.key, value) }; +} +const provide = (self, that) => ({ build: async (context, scope) => self.build(await that.build(context, scope), scope) }); +const mergeAll = (...layers) => ({ build: async (context, scope) => { + let merged = new Map(context); + for (const layer of layers) merged = new Map([...merged, ...await layer.build(context, scope)]); + return merged; +} }); +// main.js +const Store = Service("test/Store"); +const Dependency = Service("test/Dependency"); +const Audit = Service("test/Audit"); +const log = []; +const dependencyRead = () => "read"; +const dependencyPrepare = () => { + log.push("prepared"); + return "prepared"; +}; +const dependencyDescribe = () => "described"; +const makeCache = () => { + log.push("cache made"); + return /* @__PURE__ */ new Map(); +}; +const DependencyLayer = succeed(Dependency, { + read: dependencyRead, + prepare: dependencyPrepare, + describe: dependencyDescribe +}); +const AuditLayer = effect(Audit, acquireRelease(sync(() => { + log.push("audit acquired"); + return {}; +}), () => sync(() => log.push("audit released")))); +const StoreLayer = effect(Store, gen(function* () { + const dependency = yield* Dependency; + yield* Audit; + yield* sync(() => log.push("constructed")); + dependency.prepare(); + makeCache(); + const describe = (label) => `${label}:${dependency.describe()}`; + log.push(describe("init")); + const readOne = () => dependency.read(); + return Store.of({ readOne }); +})); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +const layer = provide(StoreLayer, mergeAll(DependencyLayer, AuditLayer)); +assert.strictEqual(await runPromise(provide$1(program, layer)), "read"); +assert.deepStrictEqual(log, [ + "audit acquired", + "constructed", + "prepared", + "cache made", + "init:described", + "audit released" +]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/main.js new file mode 100644 index 000000000000..2a26a6f0326f --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/lifecycle/main.js @@ -0,0 +1,80 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Everything `writeOne` uses is created while constructing: the Audit service +// is acquired, `dependency.prepare()` and `makeCache()` are called, and +// `describe` is also called during construction. All of that must still run +// after `writeOne` is removed; only `writeOne` and code it alone reaches go. +const Store = Context.Service("test/Store") +const Dependency = Context.Service("test/Dependency") +const Audit = Context.Service("test/Audit") + +const log = [] + +const dependencyRead = () => "read" +const dependencyPrepare = () => { + log.push("prepared") + return "prepared" +} +const dependencyDescribe = () => "described" +const dependencyWrite = () => "write" +const auditRecord = () => "audited" +const writeHelper = (value) => `wrote ${value}` +const makeCache = () => { + log.push("cache made") + return new Map() +} + +const DependencyLayer = Layer.succeed(Dependency, { + read: dependencyRead, + prepare: dependencyPrepare, + describe: dependencyDescribe, + 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 + const audit = yield* Audit + yield* Effect.sync(() => log.push("constructed")) + const prepared = dependency.prepare() + const cache = makeCache() + const describe = (label) => `${label}:${dependency.describe()}` + log.push(describe("init")) + const readOne = () => dependency.read() + const writeOne = () => { + cache.set(prepared, dependency.write()) + return writeHelper(`${describe("write")}:${audit.record()}`) + } + return Store.of({ readOne, writeOne }) + }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + return store.readOne() +}) + +const layer = Layer.provide(StoreLayer, Layer.mergeAll(DependencyLayer, AuditLayer)) +assert.strictEqual(await Effect.runPromise(Effect.provide(program, layer)), "read") +assert.deepStrictEqual(log, [ + "audit acquired", + "constructed", + "prepared", + "cache made", + "init:described", + "audit released" +]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/artifacts.snap new file mode 100644 index 000000000000..6dcdaf096e6c --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/artifacts.snap @@ -0,0 +1,38 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function succeed(service, value) { + if (arguments.length === 1) return (value) => succeed(service, value); + return { build: async (context) => new Map(context).set(service.key, value) }; +} +// main.js +const service = (await succeed(Service("test/Escape"), { + read: () => 1, + unused: () => 2 +}).build(/* @__PURE__ */ new Map(), [])).get("test/Escape"); +assert.strictEqual(service.unused(), 2); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/main.js new file mode 100644 index 000000000000..42b4a1c3edf3 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/main.js @@ -0,0 +1,7 @@ +import assert from "node:assert" +import { layer } from "./provider.js" + +// Control for namespace_layer_escape: the same escape through a named import. +const context = await layer.build(new Map(), []) +const service = context.get("test/Escape") +assert.strictEqual(service.unused(), 2) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/provider.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/provider.js new file mode 100644 index 000000000000..3c9c60523f7a --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/named_layer_escape/provider.js @@ -0,0 +1,7 @@ +import * as Context from "effect/Context" +import * as Layer from "effect/Layer" + +// The key stays private to this module; only the Layer is exported. +const K = Context.Service("test/Escape") + +export const layer = Layer.succeed(K, { read: () => 1, unused: () => 2 }) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/artifacts.snap new file mode 100644 index 000000000000..6dcdaf096e6c --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/artifacts.snap @@ -0,0 +1,38 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function succeed(service, value) { + if (arguments.length === 1) return (value) => succeed(service, value); + return { build: async (context) => new Map(context).set(service.key, value) }; +} +// main.js +const service = (await succeed(Service("test/Escape"), { + read: () => 1, + unused: () => 2 +}).build(/* @__PURE__ */ new Map(), [])).get("test/Escape"); +assert.strictEqual(service.unused(), 2); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/main.js new file mode 100644 index 000000000000..7ca2bac85cea --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/main.js @@ -0,0 +1,8 @@ +import assert from "node:assert" +import * as P from "./provider.js" + +// The Layer is built by hand through a namespace import, and the service is +// read from the resulting Context. Every method must be kept. +const context = await P.layer.build(new Map(), []) +const service = context.get("test/Escape") +assert.strictEqual(service.unused(), 2) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/provider.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/provider.js new file mode 100644 index 000000000000..3c9c60523f7a --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/namespace_layer_escape/provider.js @@ -0,0 +1,7 @@ +import * as Context from "effect/Context" +import * as Layer from "effect/Layer" + +// The key stays private to this module; only the Layer is exported. +const K = Context.Service("test/Escape") + +export const layer = Layer.succeed(K, { read: () => 1, unused: () => 2 }) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/artifacts.snap new file mode 100644 index 000000000000..b05019eecb01 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/artifacts.snap @@ -0,0 +1,86 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/NestedKey` used in CallExpression at 10:10 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +// provider.js +const K = Service("test/NestedKey"); +const layer = effect(Service("test/NestedOther"), gen(function* () { + return { + read: () => 1, + unused: () => 2 + }; +})); +// main.js +function retarget(key) { + key.key = "test/NestedOther"; +} +retarget(K); +const program = gen(function* () { + return (yield* K).read(); +}); +assert.strictEqual(await runPromise(provide(program, layer)), 1); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/barrel.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/barrel.js new file mode 100644 index 000000000000..504175be0b14 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/barrel.js @@ -0,0 +1,2 @@ +// Re-exports the provider module as a namespace, so consumers reach it in two hops. +export * as Provider from "./provider.js" diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/main.js new file mode 100644 index 000000000000..29b8e24452fb --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/main.js @@ -0,0 +1,16 @@ +import assert from "node:assert" +import * as Effect from "effect/Effect" +import * as B from "./barrel.js" + +// The key is retargeted through a two-hop namespace path, so yielding it finds +// the service provided for "test/NestedOther". +function retarget(key) { + key.key = "test/NestedOther" +} +retarget(B.Provider.K) + +const program = Effect.gen(function* () { + return (yield* B.Provider.K).read() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, B.Provider.layer)), 1) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/provider.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/provider.js new file mode 100644 index 000000000000..f8b584da9e82 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_key/provider.js @@ -0,0 +1,13 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +export const K = Context.Service("test/NestedKey") +const Other = Context.Service("test/NestedOther") + +export const layer = Layer.effect( + Other, + Effect.gen(function* () { + return { read: () => 1, unused: () => 2 } + }) +) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/artifacts.snap new file mode 100644 index 000000000000..f0ab0c3b2810 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/artifacts.snap @@ -0,0 +1,38 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function succeed(service, value) { + if (arguments.length === 1) return (value) => succeed(service, value); + return { build: async (context) => new Map(context).set(service.key, value) }; +} +// main.js +const context = await succeed(Service("test/NestedEscape"), { + read: () => 1, + unused: () => 2 +}).build(/* @__PURE__ */ new Map(), []); +assert.strictEqual(context.get("test/NestedEscape").unused(), 2); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/barrel.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/barrel.js new file mode 100644 index 000000000000..504175be0b14 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/barrel.js @@ -0,0 +1,2 @@ +// Re-exports the provider module as a namespace, so consumers reach it in two hops. +export * as Provider from "./provider.js" diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/main.js new file mode 100644 index 000000000000..726eca88a96f --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/main.js @@ -0,0 +1,7 @@ +import assert from "node:assert" +import * as B from "./barrel.js" + +// The Layer is built by hand through a two-hop namespace path, and the +// service is read from the resulting Context. Every method must be kept. +const context = await B.Provider.layer.build(new Map(), []) +assert.strictEqual(context.get("test/NestedEscape").unused(), 2) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/provider.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/provider.js new file mode 100644 index 000000000000..ea6e1785e968 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_namespace_layer/provider.js @@ -0,0 +1,7 @@ +import * as Context from "effect/Context" +import * as Layer from "effect/Layer" + +// The key stays private to this module; only the Layer is exported. +const K = Context.Service("test/NestedEscape") + +export const layer = Layer.succeed(K, { read: () => 1, unused: () => 2 }) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_release/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_release/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_release/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_release/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_release/artifacts.snap new file mode 100644 index 000000000000..5e8644a9b439 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_release/artifacts.snap @@ -0,0 +1,80 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const succeed = (value) => make(async () => value); +const sync = (evaluate) => make(async () => evaluate()); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const acquireRelease = (acquire, release) => make(async (context, scope) => { + const value = await acquire.run(context, scope); + scope.push(() => release(value).run(context, scope)); + return value; +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +// main.js +const K = Service("test/Nested"); +const log = []; +const layer = effect(K, acquireRelease(acquireRelease(succeed({ + read: () => 1, + inner: () => 2, + outer: () => 3 +}), (s) => sync(() => log.push(s.inner()))), (s) => sync(() => log.push(s.outer())))); +const program = gen(function* () { + return (yield* K).read(); +}); +assert.strictEqual(await runPromise(provide(program, layer)), 1); +assert.deepStrictEqual(log, [3, 2]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_release/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_release/main.js new file mode 100644 index 000000000000..0c7be52a550d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/nested_release/main.js @@ -0,0 +1,27 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Two nested acquisitions of the same object, each with a release that reads +// a different method. Both readers must count. +const K = Context.Service("test/Nested") +const log = [] + +const layer = Layer.effect( + K, + Effect.acquireRelease( + Effect.acquireRelease( + Effect.succeed({ read: () => 1, inner: () => 2, outer: () => 3 }), + (s) => Effect.sync(() => log.push(s.inner())) + ), + (s) => Effect.sync(() => log.push(s.outer())) + ) +) + +const program = Effect.gen(function* () { + return (yield* K).read() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, layer)), 1) +assert.deepStrictEqual(log, [3, 2]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/Context.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/Context.js new file mode 100644 index 000000000000..94b9d24a4328 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/Context.js @@ -0,0 +1,17 @@ +// A minimal stand-in for `effect/Context`. A service key is an Effect that +// looks its service up in the current context, as in the real package. +import { make } from "./Effect.js" + +export const Service = (key) => { + // Looked up by the key's current `key` property, as in the real package. + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`) + return context.get(self.key) + }) + self.key = key + self.of = (service) => service + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)) + return self +} + +export const get = (context, service) => context.get(service.key) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/Effect.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/Effect.js new file mode 100644 index 000000000000..aa14ce1da25a --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/Effect.js @@ -0,0 +1,63 @@ +// A minimal stand-in for `effect/Effect`, enough to run the service shaking +// fixtures. An Effect is an object whose `run(context, scope)` returns a +// Promise; `scope` collects finalizers. Only the API names and call shapes +// matter to the bundler; the real package is covered by @effect/bundle tests. +const EffectProto = { + *[Symbol.iterator]() { + return yield this + } +} + +export const make = (run) => Object.assign(Object.create(EffectProto), { run }) + +export const succeed = (value) => make(async () => value) + +export const sync = (evaluate) => make(async () => evaluate()) + +export const map = (self, f) => make(async (context, scope) => f(await self.run(context, scope))) + +export const flatMap = (self, f) => + make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)) + +export const gen = (body) => + make(async (context, scope) => { + const iterator = body() + let input + for (;;) { + const { value, done } = iterator.next(input) + if (done) return value + input = await value.run(context, scope) + } + }) + +export const acquireRelease = (acquire, release) => + make(async (context, scope) => { + const value = await acquire.run(context, scope) + scope.push(() => release(value).run(context, scope)) + return value + }) + +export const context = () => make(async (context) => context) + +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer() +} + +export const provide = (self, layer) => + make(async (context) => { + const scope = [] + try { + return await self.run(await layer.build(context, scope), scope) + } finally { + await closeScope(scope) + } + }) + +export const runPromise = async (self) => { + const scope = [] + try { + return await self.run(new Map(), scope) + } finally { + await closeScope(scope) + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/Layer.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/Layer.js new file mode 100644 index 000000000000..52e322d695ac --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/Layer.js @@ -0,0 +1,23 @@ +// A minimal stand-in for `effect/Layer`. A Layer builds a new context from the +// current one, registering finalizers in the given scope. +export function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_) + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) } +} + +export function succeed(service, value) { + if (arguments.length === 1) return (value) => succeed(service, value) + return { build: async (context) => new Map(context).set(service.key, value) } +} + +export const provide = (self, that) => ({ + build: async (context, scope) => self.build(await that.build(context, scope), scope) +}) + +export const mergeAll = (...layers) => ({ + build: async (context, scope) => { + let merged = new Map(context) + for (const layer of layers) merged = new Map([...merged, ...(await layer.build(context, scope))]) + return merged + } +}) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/package.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/package.json new file mode 100644 index 000000000000..bf5a05359688 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/node_modules/effect/package.json @@ -0,0 +1,11 @@ +{ + "name": "effect", + "version": "4.1.2", + "type": "module", + "sideEffects": false, + "exports": { + "./Context": "./Context.js", + "./Effect": "./Effect.js", + "./Layer": "./Layer.js" + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/receivers/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/receivers/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/receivers/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/receivers/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/receivers/artifacts.snap new file mode 100644 index 000000000000..d2e17e4bde25 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/receivers/artifacts.snap @@ -0,0 +1,92 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +const mergeAll = (...layers) => ({ build: async (context, scope) => { + let merged = new Map(context); + for (const layer of layers) merged = new Map([...merged, ...await layer.build(context, scope)]); + return merged; +} }); +// main.js +const DefaultParam = Service("test/DefaultParam"); +const Reassigned = Service("test/Reassigned"); +function read() { + return 1; +} +read = function() { + return this.unused(); +}; +const DefaultParamLayer = effect(DefaultParam, gen(function* () { + return DefaultParam.of({ + read: function(value = this.unused()) { + return value; + }, + unused: () => 2 + }); +})); +const ReassignedLayer = effect(Reassigned, gen(function* () { + return { + read, + unused: () => 2 + }; +})); +const program = gen(function* () { + return [(yield* DefaultParam).read(), (yield* Reassigned).read()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, mergeAll(DefaultParamLayer, ReassignedLayer))), [2, 2]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/receivers/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/receivers/main.js new file mode 100644 index 000000000000..5a075a7ab0ab --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/receivers/main.js @@ -0,0 +1,42 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Methods that read their receiver in ways the body alone does not show. +const DefaultParam = Context.Service("test/DefaultParam") +const Reassigned = Context.Service("test/Reassigned") + +function read() { + return 1 +} +read = function () { + return this.unused() +} + +const DefaultParamLayer = Layer.effect( + DefaultParam, + Effect.gen(function* () { + return DefaultParam.of({ + read: function (value = this.unused()) { + return value + }, + unused: () => 2 + }) + }) +) +const ReassignedLayer = Layer.effect( + Reassigned, + Effect.gen(function* () { + return { read, unused: () => 2 } + }) +) + +const program = Effect.gen(function* () { + return [(yield* DefaultParam).read(), (yield* Reassigned).read()] +}) + +assert.deepStrictEqual( + await Effect.runPromise(Effect.provide(program, Layer.mergeAll(DefaultParamLayer, ReassignedLayer))), + [2, 2] +) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/release_param_default/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/release_param_default/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/release_param_default/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/release_param_default/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/release_param_default/artifacts.snap new file mode 100644 index 000000000000..35ae4824a723 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/release_param_default/artifacts.snap @@ -0,0 +1,81 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const succeed = (value) => make(async () => value); +const sync = (evaluate) => make(async () => evaluate()); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const acquireRelease = (acquire, release) => make(async (context, scope) => { + const value = await acquire.run(context, scope); + scope.push(() => release(value).run(context, scope)); + return value; +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +// main.js +const K = Service("test/ReleaseParamDefault"); +const log = []; +const layer = effect(K, acquireRelease(succeed({ + read: () => 1, + unused: () => 2 +}), function(s, exit, value = arguments[0].unused()) { + return sync(() => log.push(value)); +})); +const program = gen(function* () { + return (yield* K).read(); +}); +assert.strictEqual(await runPromise(provide(program, layer)), 1); +assert.deepStrictEqual(log, [2]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/release_param_default/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/release_param_default/main.js new file mode 100644 index 000000000000..407fd518f2b6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/release_param_default/main.js @@ -0,0 +1,26 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The release callback reads the acquired object through `arguments` in a +// later parameter's default value, not in its body. +const K = Context.Service("test/ReleaseParamDefault") +const log = [] + +const layer = Layer.effect( + K, + Effect.acquireRelease( + Effect.succeed({ read: () => 1, unused: () => 2 }), + function (s, exit, value = arguments[0].unused()) { + return Effect.sync(() => log.push(value)) + } + ) +) + +const program = Effect.gen(function* () { + return (yield* K).read() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, layer)), 1) +assert.deepStrictEqual(log, [2]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/rest_release/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/rest_release/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/rest_release/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/rest_release/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/rest_release/artifacts.snap new file mode 100644 index 000000000000..e3b0a41aa7a7 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/rest_release/artifacts.snap @@ -0,0 +1,79 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const succeed = (value) => make(async () => value); +const sync = (evaluate) => make(async () => evaluate()); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const acquireRelease = (acquire, release) => make(async (context, scope) => { + const value = await acquire.run(context, scope); + scope.push(() => release(value).run(context, scope)); + return value; +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +// main.js +const K = Service("test/Rest"); +const log = []; +const layer = effect(K, acquireRelease(succeed({ + read: () => 1, + unused: () => 2 +}), (...args) => sync(() => log.push(args[0].unused())))); +const program = gen(function* () { + return (yield* K).read(); +}); +assert.strictEqual(await runPromise(provide(program, layer)), 1); +assert.deepStrictEqual(log, [2]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/rest_release/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/rest_release/main.js new file mode 100644 index 000000000000..3939710b3feb --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/rest_release/main.js @@ -0,0 +1,23 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The release callback reaches the acquired object through a rest parameter. +const K = Context.Service("test/Rest") +const log = [] + +const layer = Layer.effect( + K, + Effect.acquireRelease( + Effect.succeed({ read: () => 1, unused: () => 2 }), + (...args) => Effect.sync(() => log.push(args[0].unused())) + ) +) + +const program = Effect.gen(function* () { + return (yield* K).read() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, layer)), 1) +assert.deepStrictEqual(log, [2]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/_config.json new file mode 100644 index 000000000000..b56749faeca6 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/_config.json @@ -0,0 +1,7 @@ +{ + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/_test.mjs new file mode 100644 index 000000000000..c51d3b6167fd --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["dependencyWrite"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["dependencyRead"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/artifacts.snap new file mode 100644 index 000000000000..74706f6160d7 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/artifacts.snap @@ -0,0 +1,80 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../node_modules/effect/Effect.js +const EffectProto = { *[Symbol.iterator]() { + return yield this; +} }; +const make = (run) => Object.assign(Object.create(EffectProto), { run }); +const gen = (body) => make(async (context, scope) => { + const iterator = body(); + let input; + for (;;) { + const { value, done } = iterator.next(input); + if (done) return value; + input = await value.run(context, scope); + } +}); +const closeScope = async (scope) => { + for (const finalizer of scope.reverse()) await finalizer(); +}; +const provide$1 = (self, layer) => make(async (context) => { + const scope = []; + try { + return await self.run(await layer.build(context, scope), scope); + } finally { + await closeScope(scope); + } +}); +const runPromise = async (self) => { + const scope = []; + try { + return await self.run(/* @__PURE__ */ new Map(), scope); + } finally { + await closeScope(scope); + } +}; +// ../node_modules/effect/Context.js +const Service = (key) => { + const self = make(async (context) => { + if (!context.has(self.key)) throw new Error(`Service not found: ${self.key}`); + return context.get(self.key); + }); + self.key = key; + self.of = (service) => service; + self.use = (f) => make(async (context, scope) => f(await self.run(context, scope)).run(context, scope)); + return self; +}; +// ../node_modules/effect/Layer.js +function effect(service, effect_) { + if (arguments.length === 1) return (effect_) => effect(service, effect_); + return { build: async (context, scope) => new Map(context).set(service.key, await effect_.run(context, scope)) }; +} +function succeed(service, value) { + if (arguments.length === 1) return (value) => succeed(service, value); + return { build: async (context) => new Map(context).set(service.key, value) }; +} +const provide = (self, that) => ({ build: async (context, scope) => self.build(await that.build(context, scope), scope) }); +// main.js +const Store = Service("test/Store"); +const Dependency = Service("test/Dependency"); +const dependencyRead = () => "read"; +const DependencyLayer = succeed(Dependency, { read: dependencyRead }); +const StoreLayer = effect(Store, gen(function* () { + const dependency = yield* Dependency; + const readOne = () => dependency.read(); + return Store.of({ readOne }); +})); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +const layer = provide(StoreLayer, DependencyLayer); +assert.strictEqual(await runPromise(provide$1(program, layer)), "read"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/main.js new file mode 100644 index 000000000000..772f720e8d38 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service/transitive_demand/main.js @@ -0,0 +1,32 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// `writeOne` is the only reader of `dependency.write`. Once `writeOne` is +// removed, `write` is no longer demanded from the Dependency provider either. +const Store = Context.Service("test/Store") +const Dependency = Context.Service("test/Dependency") + +const dependencyRead = () => "read" +const dependencyWrite = () => "write" + +const DependencyLayer = Layer.succeed(Dependency, { read: dependencyRead, write: dependencyWrite }) + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const dependency = yield* Dependency + const readOne = () => dependency.read() + const writeOne = () => dependency.write() + return Store.of({ readOne, writeOne }) + }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + return store.readOne() +}) + +const layer = Layer.provide(StoreLayer, DependencyLayer) +assert.strictEqual(await Effect.runPromise(Effect.provide(program, layer)), "read") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/builtin_prototype_write/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/builtin_prototype_write/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/builtin_prototype_write/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/builtin_prototype_write/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/builtin_prototype_write/artifacts.snap new file mode 100644 index 000000000000..008ea0aab2a7 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/builtin_prototype_write/artifacts.snap @@ -0,0 +1,4688 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] builtin prototype modified or used as a value at 21:1 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] builtin prototype modified or used as a value at 27:3 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber$1 = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber$1((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber$1((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber$1((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber$1((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber$1((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber$1((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber$1((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Creates an `Effect` that always succeeds with a given value. +* +* **When to use** +* +* Use when an effect should complete successfully with a specific value without any errors +* or external dependencies. +* +* **Example** (Creating a successful effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* // Creating an effect that represents a successful scenario +* // +* // ┌─── Effect +* // ▼ +* const success = Effect.succeed(42) +* Effect.runSync(success) // => 42 +* ``` +* +* @see {@link fail} to create an effect that represents a failure. +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = succeed$1; +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides access to the current fiber within an effect computation. +* +* **Example** (Reading the current fiber) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const program = Effect.withFiber((fiber) => Effect.succeed(typeof fiber.id)) +* +* Effect.runSync(program) // => "number" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const withFiber = withFiber$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealPrototypeWrite"); +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => "unused"; + return Store.of({ + readOne, + unused + }); +})); +const maps = []; +const originalGet = Map.prototype.get; +Map.prototype.get = function(key) { + maps.push(this); + return originalGet.call(this, key); +}; +const observe = () => { + Map.prototype.get = originalGet; + const map = maps.find((map) => map.has("test/RealPrototypeWrite")); + return originalGet.call(map, "test/RealPrototypeWrite").unused(); +}; +const program = gen(function* () { + const store = yield* Store; + const context = yield* withFiber((fiber) => succeed(fiber.context)); + return [store.readOne(), observe(context)]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "unused"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/builtin_prototype_write/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/builtin_prototype_write/main.js new file mode 100644 index 000000000000..60dc000533e0 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/builtin_prototype_write/main.js @@ -0,0 +1,39 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Replacing Map.prototype.get captures the service map of a Context when Effect looks a +// service up. Every method of the service must be kept. +const Store = Context.Service("test/RealPrototypeWrite") + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => "unused" + return Store.of({ readOne, unused }) + }) +) + +const maps = [] +const originalGet = Map.prototype.get +Map.prototype.get = function (key) { + maps.push(this) + return originalGet.call(this, key) +} + +const observe = () => { + Map.prototype.get = originalGet + const map = maps.find((map) => map.has("test/RealPrototypeWrite")) + return originalGet.call(map, "test/RealPrototypeWrite").unused() +} + +const program = Effect.gen(function* () { + const store = yield* Store + // The live Context of the provided scope, through the running Fiber. + const context = yield* Effect.withFiber((fiber) => Effect.succeed(fiber.context)) + return [store.readOne(), observe(context)] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "unused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/_test.mjs new file mode 100644 index 000000000000..a698a820f53d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/_test.mjs @@ -0,0 +1,15 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["readHelper", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/artifacts.snap new file mode 100644 index 000000000000..de0d54320554 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/artifacts.snap @@ -0,0 +1,4612 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealCleanBuiltinCallback"); +const readHelper = () => "read"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + return Store.of({ readOne }); +})); +const doubled = [1, 2].map((x) => x * 2); +const program = gen(function* () { + return [(yield* Store).readOne(), Object.keys(doubled).join(",")]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "0,1"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/main.js new file mode 100644 index 000000000000..292428f55e98 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/clean_builtin_callback/main.js @@ -0,0 +1,28 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A builtin callback over clean data returns clean data, which may be +// enumerated. The pass must still remove `writeOne`. +const Store = Context.Service("test/RealCleanBuiltinCallback") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +const doubled = [1, 2].map((x) => x * 2) + +const program = Effect.gen(function* () { + return [(yield* Store).readOne(), Object.keys(doubled).join(",")] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "0,1"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/_test.mjs new file mode 100644 index 000000000000..5f4138efb95b --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/_test.mjs @@ -0,0 +1,16 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here, so a global bailout +// cannot make the suite pass. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["deadHelper", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["liveHelper", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/artifacts.snap new file mode 100644 index 000000000000..78e6870162b4 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/artifacts.snap @@ -0,0 +1,4613 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// helpers.js +const liveHelper = () => "live"; +// provider.js +const Store = Service("test/RealCrossModule"); +const layer = effect(Store, gen(function* () { + const readOne = () => liveHelper(); + return Store.of({ readOne }); +})); +// main.js +const program = gen(function* () { + return (yield* Store).readOne(); +}); +assert.strictEqual(await runPromise(provide(program, layer)), "live"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/helpers.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/helpers.js new file mode 100644 index 000000000000..49d8923c7927 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/helpers.js @@ -0,0 +1,3 @@ +// Module-level helpers for the provider in ./provider.js. +export const liveHelper = () => "live" +export const deadHelper = () => "dead" diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/main.js new file mode 100644 index 000000000000..dd7297b28bfd --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/main.js @@ -0,0 +1,10 @@ +import assert from "node:assert" +import * as Effect from "effect/Effect" +import * as P from "./provider.js" + +// The consumer and the provided Layer come from another module's namespace. +const program = Effect.gen(function* () { + return (yield* P.Store).readOne() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, P.layer)), "live") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/provider.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/provider.js new file mode 100644 index 000000000000..7d28148bff9f --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/cross_module/provider.js @@ -0,0 +1,16 @@ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as H from "./helpers.js" + +// Provider and key in their own module, helpers reached through a namespace. +export const Store = Context.Service("test/RealCrossModule") + +export const layer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => H.liveHelper() + const writeOne = () => H.deadHelper() + return Store.of({ readOne, writeOne }) + }) +) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/forged_key/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/forged_key/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/forged_key/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/forged_key/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/forged_key/artifacts.snap new file mode 100644 index 000000000000..33fb005478a1 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/forged_key/artifacts.snap @@ -0,0 +1,4671 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Context.get` looks a service up other than by `yield*` at 21:30 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber$1 = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber$1((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber$1((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber$1((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber$1((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber$1((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber$1((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber$1((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Creates an `Effect` that always succeeds with a given value. +* +* **When to use** +* +* Use when an effect should complete successfully with a specific value without any errors +* or external dependencies. +* +* **Example** (Creating a successful effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* // Creating an effect that represents a successful scenario +* // +* // ┌─── Effect +* // ▼ +* const success = Effect.succeed(42) +* Effect.runSync(success) // => 42 +* ``` +* +* @see {@link fail} to create an effect that represents a failure. +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = succeed$1; +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides access to the current fiber within an effect computation. +* +* **Example** (Reading the current fiber) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const program = Effect.withFiber((fiber) => Effect.succeed(typeof fiber.id)) +* +* Effect.runSync(program) // => "number" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const withFiber = withFiber$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealForgedKey"); +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => "unused"; + return Store.of({ + readOne, + unused + }); +})); +const observe = (context) => get(context, { key: "test/RealForgedKey" }).unused(); +const program = gen(function* () { + const store = yield* Store; + const context = yield* withFiber((fiber) => succeed(fiber.context)); + return [store.readOne(), observe(context)]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "unused"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/forged_key/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/forged_key/main.js new file mode 100644 index 000000000000..42c263026503 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/forged_key/main.js @@ -0,0 +1,30 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A hand-made key object with the same key string looks the service up without the +// tracked key. Every method of the service must be kept. +const Store = Context.Service("test/RealForgedKey") + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => "unused" + return Store.of({ readOne, unused }) + }) +) + +import * as ContextApi from "effect/Context" + +const observe = (context) => ContextApi.get(context, { key: "test/RealForgedKey" }).unused() + +const program = Effect.gen(function* () { + const store = yield* Store + // The live Context of the provided scope, through the running Fiber. + const context = yield* Effect.withFiber((fiber) => Effect.succeed(fiber.context)) + return [store.readOne(), observe(context)] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "unused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/host_module_loader/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/host_module_loader/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/host_module_loader/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/host_module_loader/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/host_module_loader/artifacts.snap new file mode 100644 index 000000000000..edb1ca5f4ea8 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/host_module_loader/artifacts.snap @@ -0,0 +1,4685 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `compileFunction` may run code outside the bundle at 21:3 in main.js + +``` + +## UNRESOLVED_IMPORT + +```text +[UNRESOLVED_IMPORT] Could not resolve 'node:process' in main.js + ╭─[ main.js:5:34 ] + │ + 5 │ import { getBuiltinModule } from "node:process" + │ ───────┬────── + │ ╰──────── Module not found, treating it as an external dependency +───╯ + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +import { getBuiltinModule } from "node:process"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber$1 = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber$1((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber$1((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber$1((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber$1((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber$1((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber$1((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber$1((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Creates an `Effect` that always succeeds with a given value. +* +* **When to use** +* +* Use when an effect should complete successfully with a specific value without any errors +* or external dependencies. +* +* **Example** (Creating a successful effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* // Creating an effect that represents a successful scenario +* // +* // ┌─── Effect +* // ▼ +* const success = Effect.succeed(42) +* Effect.runSync(success) // => 42 +* ``` +* +* @see {@link fail} to create an effect that represents a failure. +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = succeed$1; +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides access to the current fiber within an effect computation. +* +* **Example** (Reading the current fiber) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const program = Effect.withFiber((fiber) => Effect.succeed(typeof fiber.id)) +* +* Effect.runSync(program) // => "number" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const withFiber = withFiber$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealHostModuleLoader"); +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => "unused"; + return Store.of({ + readOne, + unused + }); +})); +const observe = (context) => getBuiltinModule("vm").compileFunction("return ctx.mapUnsafe.get(\"test/RealHostModuleLoader\").unused()", ["ctx"])(context); +const program = gen(function* () { + const store = yield* Store; + const context = yield* withFiber((fiber) => succeed(fiber.context)); + return [store.readOne(), observe(context)]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "unused"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/host_module_loader/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/host_module_loader/main.js new file mode 100644 index 000000000000..c139ba9b6a16 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/host_module_loader/main.js @@ -0,0 +1,30 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import { getBuiltinModule } from "node:process" + +// A host operation without a summary may run code in this realm, here through +// `process.getBuiltinModule`. Every method of the service must be kept. +const Store = Context.Service("test/RealHostModuleLoader") + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => "unused" + return Store.of({ readOne, unused }) + }) +) + +const observe = (context) => + getBuiltinModule("vm").compileFunction('return ctx.mapUnsafe.get("test/RealHostModuleLoader").unused()', ["ctx"])(context) + +const program = Effect.gen(function* () { + const store = yield* Store + // The live Context of the provided scope, through the running Fiber. + const context = yield* Effect.withFiber((fiber) => Effect.succeed(fiber.context)) + return [store.readOne(), observe(context)] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "unused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/_test.mjs new file mode 100644 index 000000000000..bc0f6400d1e3 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["readOne", "unused"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/artifacts.snap new file mode 100644 index 000000000000..c106dafde998 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/artifacts.snap @@ -0,0 +1,4624 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Context.Service` used other than to declare a service key at 9:21 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +var Store = class extends Service()("test/RealKeyClassDeclaredIdentity") { + static key = "test/RealKeyClassActualIdentity"; +}; +const Alias = Service("test/RealKeyClassActualIdentity"); +const StoreLayer = effect(Store, gen(function* () { + return Store.of({ + readOne: () => "read", + unused: () => "unused" + }); +})); +const program = gen(function* () { + return (yield* Alias).unused(); +}); +assert.strictEqual(await runPromise(provide(program, StoreLayer)), "unused"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/main.js new file mode 100644 index 000000000000..c753c149d880 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_key/main.js @@ -0,0 +1,26 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A class-form key that overrides the inherited `key`: its services live under +// the static string, not the one in the heritage, so a key declared with that +// string reads the same service. +class Store extends Context.Service()("test/RealKeyClassDeclaredIdentity") { + static key = "test/RealKeyClassActualIdentity" +} +const Alias = Context.Service("test/RealKeyClassActualIdentity") + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + return Store.of({ readOne: () => "read", unused: () => "unused" }) + }) +) + +const program = Effect.gen(function* () { + const alias = yield* Alias + return alias.unused() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), "unused") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/_test.mjs new file mode 100644 index 000000000000..a21f88129a0f --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/artifacts.snap new file mode 100644 index 000000000000..741b8352b203 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/artifacts.snap @@ -0,0 +1,4626 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Context.Service` used other than to declare a service key at 9:21 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +var Store = class extends Service()("test/RealKeyClassOverridesOf") { + static of(value) { + return { readOne: () => value.unused() }; + } +}; +const StoreLayer = effect(Store, gen(function* () { + const unusedHelper = () => "unused"; + return Store.of({ + readOne: () => "read", + unused: () => unusedHelper() + }); +})); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +assert.strictEqual(await runPromise(provide(program, StoreLayer)), "unused"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/main.js new file mode 100644 index 000000000000..136b50930396 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_overrides_of/main.js @@ -0,0 +1,28 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A class-form key that overrides the inherited `of`: `Store.of(value)` is no +// longer the identity, and here it reads a method of its argument that no +// consumer reads directly. +class Store extends Context.Service()("test/RealKeyClassOverridesOf") { + static of(value) { + return { readOne: () => value.unused() } + } +} + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const unusedHelper = () => "unused" + return Store.of({ readOne: () => "read", unused: () => unusedHelper() }) + }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + return store.readOne() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), "unused") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/_test.mjs new file mode 100644 index 000000000000..1c49008ee2ac --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} +for (const name of []) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/artifacts.snap new file mode 100644 index 000000000000..d6a3c8bbf2e9 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/artifacts.snap @@ -0,0 +1,4645 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Context.Service` used other than to declare a service key at 8:21 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map$1 = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map$1(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map$1((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Transforms the value inside an effect by applying a function to it. +* +* **When to use** +* +* Use to transform an effect's success value with a function that returns a +* plain value, producing a new effect without changing the original effect's +* typed error or context requirements. +* +* **Details** +* +* `map` takes a function and applies it to the value contained within an +* effect, creating a new effect with the transformed value. +* +* It's important to note that effects are immutable, meaning that the original +* effect is not modified. Instead, a new effect is returned with the updated +* value. +* +* **Example** (Choosing map syntax variants) +* +* ```ts import.meta.vitest +* import { Effect, pipe } from "effect" +* const output: Array = [] +* +* const myEffect = Effect.succeed(1) +* const transformation = (n: number) => n + 1 +* +* const mappedWithPipe = pipe(myEffect, Effect.map(transformation)) +* const mappedWithDataFirst = Effect.map(myEffect, transformation) +* const mappedWithMethod = myEffect.pipe(Effect.map(transformation)) +* +* void output.push(Effect.runSync(Effect.all([ +* mappedWithPipe, +* mappedWithDataFirst, +* mappedWithMethod +* ]))) +* output // => [[2, 2, 2]] +* ``` +* +* **Example** (Adding a service charge) +* +* ```ts import.meta.vitest +* import { Effect, pipe } from "effect" +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const finalAmount = pipe( +* fetchTransactionAmount, +* Effect.map(addServiceCharge) +* ) +* +* await Effect.runPromise(finalAmount) // => 101 +* ``` +* +* @see {@link mapError} for a version that operates on the error channel. +* @see {@link mapBoth} for a version that operates on both channels. +* @see {@link flatMap} or {@link andThen} for a version that can return a new effect. +* @stability stable +* @category mapping +* @since 2.0.0 +*/ +const map = map$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +var Store = class extends Service()("test/RealKeyClassStaticMember") { + static readUnused() { + return map(this, (store) => store.unused()); + } +}; +const unusedHelper = () => "unused"; +const StoreLayer = succeed(Store, { + readOne: () => "read", + unused: () => unusedHelper() +}); +const program = gen(function* () { + return [(yield* Store).readOne(), yield* Store.readUnused()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "unused"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/main.js new file mode 100644 index 000000000000..6c77cba03c7d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/key_class_static_member/main.js @@ -0,0 +1,23 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A class-form key whose body reads the service through `this`, a use of the +// key the pass does not model. Every method of the service stays. +class Store extends Context.Service()("test/RealKeyClassStaticMember") { + static readUnused() { + return Effect.map(this, (store) => store.unused()) + } +} + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.succeed(Store, { readOne: () => "read", unused: () => unusedHelper() }) + +const program = Effect.gen(function* () { + const store = yield* Store + return [store.readOne(), yield* Store.readUnused()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "unused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/_test.mjs new file mode 100644 index 000000000000..eade95cfa58d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/_test.mjs @@ -0,0 +1,16 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here, so a global bailout +// cannot make the suite pass. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "dependencyWrite", "auditRecord", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["dependencyPrepare", "dependencyDescribe", "makeCache", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/artifacts.snap new file mode 100644 index 000000000000..ff75cc09908c --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/artifacts.snap @@ -0,0 +1,4968 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync$1(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync$1 = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const succeedPayload = function(_value, fiber) { + return fiber.succeedWith(this.payload); +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +const tapCont = function(value) { + const f = this.payload; + return new ContImpl(f(value), succeedPayload, value); +}; +const tapEffectCont = function(value) { + return new ContImpl(this.payload, succeedPayload, value); +}; +/** @internal */ +const tap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, isEffect(f) ? tapEffectCont : tapCont, f)); +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const contextWith = (f) => withFiber((fiber) => f(fiber.context)); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerExit = (scope, finalizer) => { + return suspend(() => { + if (scope.state._tag === "Closed") return finalizer(scope.state.exit); + scopeAddFinalizerUnsafe(scope, {}, finalizer); + return void_; + }); +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scope = scopeTag; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +/** @internal */ +const acquireRelease$1 = (acquire, release, options) => contextWith((context) => uninterruptibleMask((restore) => flatMap(scope, (scope) => tap(options?.interruptible ? restore(acquire) : acquire, (a) => scopeAddFinalizerExit(scope, (exit) => provideContext(release(a, exit), context)))))); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptible = /*#__PURE__*/ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}); +const setInterruptibleTrue = /*#__PURE__*/ setInterruptible(true); +const setInterruptibleFalse = /*#__PURE__*/ setInterruptible(false); +const setFiberInterruptible = (fiber) => { + fiber.interruptible = true; + fiber._stack.push(setInterruptibleFalse); + if (fiber._interruptedCause) return failCause(fiber._interruptedCause); +}; +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const interruptible = (self) => withFiber((fiber) => { + if (fiber.interruptible) return self; + return setFiberInterruptible(fiber) ?? self; +}); +/** @internal */ +const uninterruptibleMask = (f) => withFiber((fiber) => { + if (!fiber.interruptible) return f(identity); + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return f(interruptible); +}); +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync$1(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$3 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$3(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +const provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map((merged) => f(merged, context))))); +/** +* Feeds the output services of the dependency layer into the requirements of +* this layer, returning a layer that only provides the services from this layer. +* +* **When to use** +* +* Use when you need to hide an implementation dependency layer from callers. +* +* **Details** +* +* In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is +* built first and is used to satisfy the requirements of `serviceLayer`. +* +* **Example** (Providing layer dependencies) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class UserService extends Context.Service Effect.Effect<{ +* id: string +* name: string +* }> +* }>()("UserService") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* // Create dependency layers +* const databaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) +* }) +* +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(`[LOG] ${msg}`))) +* }) +* +* // UserService depends on Database and Logger +* const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { +* const database = yield* Database +* const logger = yield* Logger +* +* return { +* getUser: Effect.fn("UserService.getUser")(function*(id: string) { +* yield* logger.log(`Looking up user ${id}`) +* const result = yield* database.query( +* `SELECT * FROM users WHERE id = ${id}` +* ) +* return { id, name: result } +* }) +* } +* })) +* +* // Provide dependencies to UserService layer +* const userServiceWithDependencies = userServiceLayer.pipe( +* Layer.provide(Layer.mergeAll(databaseLayer, loggerLayer)) +* ) +* +* // Now UserService layer has no dependencies +* const program = Effect.gen(function*() { +* const userService = yield* UserService +* return yield* userService.getUser("123") +* }).pipe( +* Effect.provide(userServiceWithDependencies) +* ) +* Effect.runSync(program) // => { id: "123", name: "DB: SELECT * FROM users WHERE id = 123" } +* logs // => ["[LOG] Looking up user 123"] +* ``` +* +* @see {@link provideMerge} for retaining the dependency services +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide$2 = /*#__PURE__*/ dual(2, (self, that) => provideWith(self, that, identity)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Creates an `Effect` that represents a synchronous side-effectful computation. +* +* **When to use** +* +* Use when you need to wrap a synchronous side-effectful operation that is not +* expected to throw. +* +* **Details** +* +* The provided function is evaluated lazily when the effect runs. +* +* **Gotchas** +* +* The function must not throw. If it throws, the thrown value is treated as a +* defect, not as a typed failure. Use `try` when throwing is expected. +* +* **Example** (Capturing synchronous logging in an Effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* const log = (message: string) => +* Effect.sync(() => { +* void output.push(message) // side effect +* }) +* +* // ┌─── Effect +* // ▼ +* const program = log("Hello, World!") +* Effect.runSync(program) +* output // => ["Hello, World!"] +* ``` +* +* @see {@link try_ | try} for a version that can handle failures. +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const sync = sync$1; +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Constructs a scoped resource from an acquisition effect and a release +* finalizer. +* +* **When to use** +* +* Use to acquire a scoped resource with an explicit release finalizer. +* +* **Details** +* +* If acquisition succeeds, the release finalizer is added to the current scope +* and is guaranteed to run when that scope closes. The finalizer receives the +* `Exit` value used to close the scope. +* +* By default, acquisition is protected by an uninterruptible region. Pass +* `{ interruptible: true }` to allow the acquisition effect to be interrupted. +* +* **Example** (Acquiring and releasing a resource) +* +* ```ts import.meta.vitest +* import { Effect, Exit } from "effect" +* const output: Array = [] +* +* // Simulate a resource that needs cleanup +* interface FileHandle { +* readonly path: string +* readonly content: string +* } +* +* // Acquire a file handle +* const acquire = Effect.gen(function*() { +* yield* Effect.sync(() => { output.push("Opening file") }) +* return { path: "/tmp/file.txt", content: "file content" } +* }) +* +* // Release the file handle +* const release = (handle: FileHandle, exit: Exit.Exit) => +* Effect.sync(() => { output.push( +* `Closing file ${handle.path} with exit: ${ +* Exit.isSuccess(exit) ? "success" : "failure" +* }` +* ) }) +* +* // Create a scoped resource +* const resource = Effect.acquireRelease(acquire, release) +* +* // Use the resource within a scope +* const program = Effect.scoped( +* Effect.gen(function*() { +* const handle = yield* resource +* yield* Effect.sync(() => { output.push(`Using file: ${handle.path}`) }) +* return handle.content +* }) +* ) +* +* void output.push(Effect.runSync(program)) +* output // => ["Opening file", "Using file: /tmp/file.txt", "Closing file /tmp/file.txt with exit: success", "file content"] +* ``` +* +* @see {@link acquireDisposable} for resources that implement JavaScript disposal protocols +* @see {@link acquireUseRelease} for bracketing acquire, use, and release in one effect +* +* @stability stable +* @category resource management +* @since 2.0.0 +*/ +const acquireRelease = acquireRelease$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealStore"); +const Dependency = Service("test/RealDependency"); +const Audit = Service("test/RealAudit"); +const log = []; +const dependencyRead = () => "read"; +const dependencyPrepare = () => { + log.push("prepared"); + return "prepared"; +}; +const dependencyDescribe = () => "described"; +const makeCache = () => { + log.push("cache made"); + return /* @__PURE__ */ new Map(); +}; +const DependencyLayer = succeed(Dependency, { + read: dependencyRead, + prepare: dependencyPrepare, + describe: dependencyDescribe +}); +const AuditLayer = effect(Audit, acquireRelease(sync(() => { + log.push("audit acquired"); + return {}; +}), () => sync(() => log.push("audit released")))); +const StoreLayer = effect(Store, gen(function* () { + const dependency = yield* Dependency; + yield* Audit; + yield* sync(() => log.push("constructed")); + dependency.prepare(); + makeCache(); + const describe = (label) => `${label}:${dependency.describe()}`; + log.push(describe("init")); + const readOne = () => dependency.read(); + return Store.of({ readOne }); +})); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +const layer = provide$2(StoreLayer, mergeAll(DependencyLayer, AuditLayer)); +assert.strictEqual(await runPromise(provide(program, layer)), "read"); +assert.deepStrictEqual(log, [ + "audit acquired", + "constructed", + "prepared", + "cache made", + "init:described", + "audit released" +]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/main.js new file mode 100644 index 000000000000..7d17810be0a9 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lifecycle/main.js @@ -0,0 +1,77 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Real Effect: `writeOne`, and everything only it uses, can be removed, while +// acquisition, construction-time calls and release keep running in order. +const Store = Context.Service("test/RealStore") +const Dependency = Context.Service("test/RealDependency") +const Audit = Context.Service("test/RealAudit") + +const log = [] + +const dependencyRead = () => "read" +const dependencyPrepare = () => { + log.push("prepared") + return "prepared" +} +const dependencyDescribe = () => "described" +const dependencyWrite = () => "write" +const auditRecord = () => "audited" +const writeHelper = (value) => `wrote ${value}` +const makeCache = () => { + log.push("cache made") + return new Map() +} + +const DependencyLayer = Layer.succeed(Dependency, { + read: dependencyRead, + prepare: dependencyPrepare, + describe: dependencyDescribe, + 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 + const audit = yield* Audit + yield* Effect.sync(() => log.push("constructed")) + const prepared = dependency.prepare() + const cache = makeCache() + const describe = (label) => `${label}:${dependency.describe()}` + log.push(describe("init")) + const readOne = () => dependency.read() + const writeOne = () => { + cache.set(prepared, dependency.write()) + return writeHelper(`${describe("write")}:${audit.record()}`) + } + return Store.of({ readOne, writeOne }) + }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + return store.readOne() +}) + +const layer = Layer.provide(StoreLayer, Layer.mergeAll(DependencyLayer, AuditLayer)) +assert.strictEqual(await Effect.runPromise(Effect.provide(program, layer)), "read") +assert.deepStrictEqual(log, [ + "audit acquired", + "constructed", + "prepared", + "cache made", + "init:described", + "audit released" +]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/_test.mjs new file mode 100644 index 000000000000..790242d46c8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The pass is turned off: every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/artifacts.snap new file mode 100644 index 000000000000..aa03544e5681 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/artifacts.snap @@ -0,0 +1,4625 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] host capability read by a non-constant name at 22:3 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLoaderComputedAccess"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const load = () => process[["getBuiltin", "Module"].join("")]("vm")[["compile", "Function"].join("")]("return 1")(); +const program = gen(function* () { + return [(yield* Store).readOne(), load()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", 1]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/main.js new file mode 100644 index 000000000000..3dd1a0135735 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_computed_access/main.js @@ -0,0 +1,29 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A code loader reached through non-constant names on the host `process` still +// loads code outside the bundle (A2). +const Store = Context.Service("test/RealLoaderComputedAccess") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const load = () => + process[["getBuiltin", "Module"].join("")]("vm")[["compile", "Function"].join("")]("return 1")() + +const program = Effect.gen(function* () { + const store = yield* Store + return [store.readOne(), load()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", 1]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/_test.mjs new file mode 100644 index 000000000000..790242d46c8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The pass is turned off: every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/artifacts.snap new file mode 100644 index 000000000000..74ea289f36d4 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/artifacts.snap @@ -0,0 +1,4625 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `constructor` may run code outside the bundle at 23:14 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLoaderFunctionConstructorArrow"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const load = (() => 0)["constructor"]; +const program = gen(function* () { + return [(yield* Store).readOne(), load("return 1")()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", 1]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/main.js new file mode 100644 index 000000000000..fff3f3642776 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_arrow/main.js @@ -0,0 +1,30 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The Function constructor, reached through a constant computed name on an +// ordinary function, loads code outside the bundle (A2). A name known only at +// run time, such as `["con", "structor"].join("")`, is outside the contract: +// the app is assumed not to build one, and the pass does not detect it. +const Store = Context.Service("test/RealLoaderFunctionConstructorArrow") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const load = (() => 0)["con" + "structor"] + +const program = Effect.gen(function* () { + const store = yield* Store + return [store.readOne(), load("return 1")()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", 1]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/_test.mjs new file mode 100644 index 000000000000..790242d46c8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The pass is turned off: every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/artifacts.snap new file mode 100644 index 000000000000..6d53738f587d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/artifacts.snap @@ -0,0 +1,4625 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `constructor` may run code outside the bundle at 23:14 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLoaderFunctionConstructorGlobal"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const load = globalThis.Object["constructor"]; +const program = gen(function* () { + return [(yield* Store).readOne(), load("return 1")()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", 1]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/main.js new file mode 100644 index 000000000000..83d6acd996e4 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_function_constructor_global/main.js @@ -0,0 +1,30 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The Function constructor, reached through a constant computed name on a +// global builtin, loads code outside the bundle (A2). A name known only at run +// time, such as `["con", "structor"].join("")`, is outside the contract: the +// app is assumed not to build one, and the pass does not detect it. +const Store = Context.Service("test/RealLoaderFunctionConstructorGlobal") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const load = globalThis.Object["con" + "structor"] + +const program = Effect.gen(function* () { + const store = yield* Store + return [store.readOne(), load("return 1")()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", 1]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/_test.mjs new file mode 100644 index 000000000000..790242d46c8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The pass is turned off: every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/artifacts.snap new file mode 100644 index 000000000000..8613f63f85ee --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/artifacts.snap @@ -0,0 +1,4638 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] host operation that loads code at 24:28 in main.js + +``` + +## UNRESOLVED_IMPORT + +```text +[UNRESOLVED_IMPORT] Could not resolve 'node:vm' in loader.js + ╭─[ loader.js:2:44 ] + │ + 2 │ export { compileFunction as compile } from "node:vm" + │ ────┬──── + │ ╰────── Module not found, treating it as an external dependency +───╯ + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +import { compileFunction as compile } from "node:vm"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLoaderReexport"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const program = gen(function* () { + return [(yield* Store).readOne(), compile("return 1")()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", 1]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/loader.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/loader.js new file mode 100644 index 000000000000..3596b5850766 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/loader.js @@ -0,0 +1,2 @@ +// Re-exports a code loader under another name. +export { compileFunction as compile } from "node:vm" diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/main.js new file mode 100644 index 000000000000..d8b99aa46621 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reexport/main.js @@ -0,0 +1,27 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import { compile } from "./loader.js" + +// A code loader reached through a renamed re-export of `node:vm` still loads code +// outside the bundle (A2). +const Store = Context.Service("test/RealLoaderReexport") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + return [store.readOne(), compile("return 1")()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", 1]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/_test.mjs new file mode 100644 index 000000000000..790242d46c8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The pass is turned off: every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/artifacts.snap new file mode 100644 index 000000000000..f77008997e2b --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/artifacts.snap @@ -0,0 +1,4625 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `constructor` may run code outside the bundle at 22:14 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLoaderReflectGet"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const load = Reflect.get(() => 0, "constructor"); +const program = gen(function* () { + return [(yield* Store).readOne(), load("return 1")()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", 1]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/main.js new file mode 100644 index 000000000000..e12e89832532 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get/main.js @@ -0,0 +1,29 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The Function constructor, read through `Reflect.get` with a literal name, +// loads code outside the bundle (A2). The name is a call argument rather than +// a member name, but it is still known at compile time. +const Store = Context.Service("test/RealLoaderReflectGet") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const load = Reflect.get(() => 0, "constructor") + +const program = Effect.gen(function* () { + const store = yield* Store + return [store.readOne(), load("return 1")()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", 1]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/_test.mjs new file mode 100644 index 000000000000..790242d46c8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The pass is turned off: every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/artifacts.snap new file mode 100644 index 000000000000..d7c4aec1f631 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/artifacts.snap @@ -0,0 +1,4641 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `constructor` may run code outside the bundle at 22:14 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `constructor` may run code outside the bundle at 24:19 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLoaderReflectGetGlobal"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const load = globalThis.Reflect.get(() => 0, "constructor"); +const loadAgain = globalThis.Reflect.get(() => 0, "constructor"); +const program = gen(function* () { + return [ + (yield* Store).readOne(), + load("return 1")(), + loadAgain("return 2")() + ]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), [ + "read", + 1, + 2 +]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/main.js new file mode 100644 index 000000000000..8070175bbe70 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_global/main.js @@ -0,0 +1,31 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The Function constructor, read through `Reflect.get` on `globalThis.Reflect` +// with a literal name, loads code outside the bundle (A2). The second load +// reaches the same builtin through an alias of `globalThis.Reflect`. +const Store = Context.Service("test/RealLoaderReflectGetGlobal") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const load = globalThis.Reflect.get(() => 0, "constructor") +const reflect = globalThis.Reflect +const loadAgain = reflect.get(() => 0, "constructor") + +const program = Effect.gen(function* () { + const store = yield* Store + return [store.readOne(), load("return 1")(), loadAgain("return 2")()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", 1, 2]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/_test.mjs new file mode 100644 index 000000000000..790242d46c8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The pass is turned off: every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/artifacts.snap new file mode 100644 index 000000000000..4c05943b1c3a --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/artifacts.snap @@ -0,0 +1,4625 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `get` called with a spread before the key at 22:14 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLoaderReflectGetSpread"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const load = Reflect.get(...[], () => 0, "constructor"); +const program = gen(function* () { + return [(yield* Store).readOne(), load("return 1")()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", 1]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/main.js new file mode 100644 index 000000000000..480ceb876b5b --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/loader_reflect_get_spread/main.js @@ -0,0 +1,29 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The Function constructor, read through `Reflect.get` with a literal name, +// loads code outside the bundle (A2). The spread moves that name to the +// second argument at run time, though it is the third one in the source. +const Store = Context.Service("test/RealLoaderReflectGetSpread") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const load = Reflect.get(...[], () => 0, "constructor") + +const program = Effect.gen(function* () { + const store = yield* Store + return [store.readOne(), load("return 1")()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", 1]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/_test.mjs new file mode 100644 index 000000000000..05e0682e28b9 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/artifacts.snap new file mode 100644 index 000000000000..42ef14246515 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/artifacts.snap @@ -0,0 +1,4818 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Context.get` looks a service up other than by `yield*` at 21:10 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/RealLookupSpreadOther` used in CallExpression at 21:75 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge$1 = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const context$1 = () => getContext; +const getContext = /*#__PURE__*/ withFiber((fiber) => succeed$1(fiber.context)); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge$1(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +/** +* Merges this layer with another layer concurrently, producing a new layer with +* combined input, error, and output types. +* +* **When to use** +* +* Use to combine an existing `Layer` with another `Layer` or an array of +* layers while preserving pipeline style. +* +* **Details** +* +* This is a binary version of `mergeAll` that merges exactly two layers or one +* layer with an array of layers. The layers are built concurrently and their +* outputs are combined. +* +* **Example** (Merging two layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((_msg: string) => Effect.void) +* }) +* +* const mergedLayer = Layer.merge(dbLayer, loggerLayer) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, mergedLayer)) // => "result" +* ``` +* +* @see {@link mergeAll} for merging several layers at once +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => mergeAll(self, ...Array.isArray(that) ? that : [that])); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Returns the complete context. +* +* **When to use** +* +* Use to read the complete `Context` available to the current effect. +* +* **Details** +* +* This function allows you to access all services that are currently available +* in the effect's environment. This can be useful for debugging, introspection, +* or when you need to pass the entire context to another function. +* +* **Example** (Reading the full context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Option } from "effect" +* const output: Array = [] +* +* const Logger = Context.Service<{ +* log: (msg: string) => void +* }>("Logger") +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* const program = Effect.gen(function*() { +* const allServices = yield* Effect.context() +* +* // Check if specific services are available +* const loggerOption = Context.getOption(allServices, Logger) +* const databaseOption = Context.getOption(allServices, Database) +* +* yield* Effect.sync(() => { output.push(`Logger available: ${Option.isSome(loggerOption)}`) }) +* yield* Effect.sync(() => { output.push(`Database available: ${Option.isSome(databaseOption)}`) }) +* }) +* +* const context = Context.make(Logger, { log: () => {} }) +* .pipe(Context.add(Database, { query: () => "result" })) +* +* const provided = Effect.provideContext(program, context) +* Effect.runSync(provided) +* output // => ["Logger available: true", "Database available: true"] +* ``` +* +* @see {@link contextWith} for deriving an effect from the complete context +* @see {@link service} for reading one service from the context +* +* @stability stable +* @category accessors +* @since 2.0.0 +*/ +const context = context$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLookupSpreadStore"); +const Other = Service("test/RealLookupSpreadOther"); +const StoreLayer = effect(Store, gen(function* () { + return Store.of({ + readOne: () => "read", + unused: () => "unused" + }); +})); +const OtherLayer = succeed(Other, { ok: () => "ok" }); +const program = gen(function* () { + const context$2 = yield* context(); + return get(...[context$2, { key: "test/RealLookupSpreadStore" }], Other).unused(); +}); +assert.strictEqual(await runPromise(provide(program, merge(StoreLayer, OtherLayer))), "unused"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/main.js new file mode 100644 index 000000000000..1a63b86569fa --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_spread_arguments/main.js @@ -0,0 +1,27 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A spread moves the key argument of a keyed lookup: at run time the second +// argument is a hand-made key for `Store`, and the trailing `Other` is ignored. +const Store = Context.Service("test/RealLookupSpreadStore") +const Other = Context.Service("test/RealLookupSpreadOther") + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + return Store.of({ readOne: () => "read", unused: () => "unused" }) + }) +) +const OtherLayer = Layer.succeed(Other, { ok: () => "ok" }) + +const program = Effect.gen(function* () { + const context = yield* Effect.context() + return Context.get(...[context, { key: "test/RealLookupSpreadStore" }], Other).unused() +}) + +assert.strictEqual( + await Effect.runPromise(Effect.provide(program, Layer.merge(StoreLayer, OtherLayer))), + "unused" +) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/_test.mjs new file mode 100644 index 000000000000..dfeb7869bf14 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["storeUnused", "storeUnusedHelper", "configUnused", "configUnusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} +for (const name of ["otherUnused", "otherUnusedHelper"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/artifacts.snap new file mode 100644 index 000000000000..3db9f4f5c5ca --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/artifacts.snap @@ -0,0 +1,4741 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets the service for a key, throwing if an absent non-reference key cannot be +* resolved. +* +* **When to use** +* +* Use when you need to read a service from a context whose type does not prove +* the service is present. +* +* **Details** +* +* If the key is a `Context.Reference` and no override is stored in the +* context, its cached default value is returned. For absent non-reference keys, +* this function throws a runtime error. +* +* **Example** (Getting services unsafely) +* +* ```ts import.meta.vitest +* import { Context, Option } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.getUnsafe(context, Port).PORT // => 8080 +* Context.getOption(context, Timeout) // => Option.none() +* ``` +* +* @see {@link get} for type-checked service access +* @see {@link getOption} for optional service access +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const getUnsafe = /*#__PURE__*/ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = getUnsafe; +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const updateService$1 = /*#__PURE__*/ dual(3, (self, service, f) => updateContext(self, (s) => { + const prev = getUnsafe(s, service); + const next = f(prev); + if (prev === next) return s; + return add(s, service, next); +})); +/** @internal */ +const context$1 = () => getContext; +const getContext = /*#__PURE__*/ withFiber((fiber) => succeed$1(fiber.context)); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Returns the complete context. +* +* **When to use** +* +* Use to read the complete `Context` available to the current effect. +* +* **Details** +* +* This function allows you to access all services that are currently available +* in the effect's environment. This can be useful for debugging, introspection, +* or when you need to pass the entire context to another function. +* +* **Example** (Reading the full context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Option } from "effect" +* const output: Array = [] +* +* const Logger = Context.Service<{ +* log: (msg: string) => void +* }>("Logger") +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* const program = Effect.gen(function*() { +* const allServices = yield* Effect.context() +* +* // Check if specific services are available +* const loggerOption = Context.getOption(allServices, Logger) +* const databaseOption = Context.getOption(allServices, Database) +* +* yield* Effect.sync(() => { output.push(`Logger available: ${Option.isSome(loggerOption)}`) }) +* yield* Effect.sync(() => { output.push(`Database available: ${Option.isSome(databaseOption)}`) }) +* }) +* +* const context = Context.make(Logger, { log: () => {} }) +* .pipe(Context.add(Database, { query: () => "result" })) +* +* const provided = Effect.provideContext(program, context) +* Effect.runSync(provided) +* output // => ["Logger available: true", "Database available: true"] +* ``` +* +* @see {@link contextWith} for deriving an effect from the complete context +* @see {@link service} for reading one service from the context +* +* @stability stable +* @category accessors +* @since 2.0.0 +*/ +const context = context$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Runs an effect with a service implementation transformed by the provided +* function. +* +* **Details** +* +* The service must be available in the effect's context; `updateService` +* replaces it for the wrapped effect with the value returned by the updater. +* +* **Example** (Replacing a service for one effect) +* +* ```ts import.meta.vitest +* import { Context, Effect } from "effect" +* const output: Array = [] +* +* // Define a counter service +* const Counter = Context.Service<{ count: number }>("Counter") +* +* const program = Effect.gen(function*() { +* const updatedCounter = yield* Effect.service(Counter) +* yield* Effect.sync(() => { output.push(`Updated count: ${updatedCounter.count}`) }) +* return updatedCounter.count +* }).pipe( +* Effect.updateService(Counter, (counter) => ({ count: counter.count + 1 })) +* ) +* +* // Provide initial service and run +* const result = Effect.provideService(program, Counter, { count: 0 }) +* void output.push(Effect.runSync(result)) +* output // => ["Updated count: 1", 1] +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const updateService = updateService$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLookupTrackedStore"); +const Config = Service("test/RealLookupTrackedConfig"); +const Other = Service("test/RealLookupTrackedOther"); +const storeUnusedHelper = () => "storeUnused"; +const configUnusedHelper = () => "configUnused"; +const layer = mergeAll(succeed(Store, { + readOne: () => "read", + storeUnused: () => storeUnusedHelper() +}), succeed(Config, { + name: () => "config", + configUnused: () => configUnusedHelper() +}), succeed(Other, { readOther: () => "other" })); +const observed = []; +const readStore = gen(function* () { + return (yield* Store).readOne(); +}); +const program = gen(function* () { + const other = yield* Other; + const first = yield* updateService(readStore, Store, (store) => { + observed.push(store.storeUnused()); + return store; + }); + const second = yield* readStore.pipe(updateService(Store, (store) => { + observed.push(store.storeUnused()); + return store; + })); + const context$2 = yield* context(); + const config = getOrUndefined(context$2, Config); + const sameConfig = getOrUndefined(Config)(context$2); + return [ + other.readOther(), + first, + second, + observed, + config.configUnused(), + sameConfig === config + ]; +}); +assert.deepStrictEqual(await runPromise(provide(program, layer)), [ + "other", + "read", + "read", + ["storeUnused", "storeUnused"], + "configUnused", + true +]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/main.js new file mode 100644 index 000000000000..97d37c8c4205 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_tracked_key/main.js @@ -0,0 +1,52 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Keyed lookups other than `yield*` by tracked keys, in both dual forms. They +// hand each service to code the pass does not follow, so `Store` and `Config` +// keep every method. `Other` is only read through `yield*`, so its unread +// method can still go. +const Store = Context.Service("test/RealLookupTrackedStore") +const Config = Context.Service("test/RealLookupTrackedConfig") +const Other = Context.Service("test/RealLookupTrackedOther") + +const storeUnusedHelper = () => "storeUnused" +const configUnusedHelper = () => "configUnused" +const otherUnusedHelper = () => "otherUnused" + +const layer = Layer.mergeAll( + Layer.succeed(Store, { readOne: () => "read", storeUnused: () => storeUnusedHelper() }), + Layer.succeed(Config, { name: () => "config", configUnused: () => configUnusedHelper() }), + Layer.succeed(Other, { readOther: () => "other", otherUnused: () => otherUnusedHelper() }) +) + +const observed = [] +const readStore = Effect.gen(function* () { + return (yield* Store).readOne() +}) + +const program = Effect.gen(function* () { + const other = yield* Other + const first = yield* Effect.updateService(readStore, Store, (store) => { + observed.push(store.storeUnused()) + return store + }) + const second = yield* readStore.pipe(Effect.updateService(Store, (store) => { + observed.push(store.storeUnused()) + return store + })) + const context = yield* Effect.context() + const config = Context.getOrUndefined(context, Config) + const sameConfig = Context.getOrUndefined(Config)(context) + return [other.readOther(), first, second, observed, config.configUnused(), sameConfig === config] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, layer)), [ + "other", + "read", + "read", + ["storeUnused", "storeUnused"], + "configUnused", + true +]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/_test.mjs new file mode 100644 index 000000000000..c9e4c3dee3cd --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["storeUnused", "storeUnusedHelper", "otherUnused", "otherUnusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} +for (const name of []) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/artifacts.snap new file mode 100644 index 000000000000..ae783d25e231 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/artifacts.snap @@ -0,0 +1,4657 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Context.getOrUndefined` looks a service up other than by `yield*` at 24:47 in main.js + +``` + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] service key `test/RealLookupUnresolvedOther` used in VariableDeclarator at 22:35 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const context$1 = () => getContext; +const getContext = /*#__PURE__*/ withFiber((fiber) => succeed$1(fiber.context)); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Returns the complete context. +* +* **When to use** +* +* Use to read the complete `Context` available to the current effect. +* +* **Details** +* +* This function allows you to access all services that are currently available +* in the effect's environment. This can be useful for debugging, introspection, +* or when you need to pass the entire context to another function. +* +* **Example** (Reading the full context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Option } from "effect" +* const output: Array = [] +* +* const Logger = Context.Service<{ +* log: (msg: string) => void +* }>("Logger") +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* const program = Effect.gen(function*() { +* const allServices = yield* Effect.context() +* +* // Check if specific services are available +* const loggerOption = Context.getOption(allServices, Logger) +* const databaseOption = Context.getOption(allServices, Database) +* +* yield* Effect.sync(() => { output.push(`Logger available: ${Option.isSome(loggerOption)}`) }) +* yield* Effect.sync(() => { output.push(`Database available: ${Option.isSome(databaseOption)}`) }) +* }) +* +* const context = Context.make(Logger, { log: () => {} }) +* .pipe(Context.add(Database, { query: () => "result" })) +* +* const provided = Effect.provideContext(program, context) +* Effect.runSync(provided) +* output // => ["Logger available: true", "Database available: true"] +* ``` +* +* @see {@link contextWith} for deriving an effect from the complete context +* @see {@link service} for reading one service from the context +* +* @stability stable +* @category accessors +* @since 2.0.0 +*/ +const context = context$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealLookupUnresolvedStore"); +const Other = Service("test/RealLookupUnresolvedOther"); +const storeUnusedHelper = () => "storeUnused"; +const otherUnusedHelper = () => "otherUnused"; +const layer = mergeAll(succeed(Store, { + readOne: () => "read", + storeUnused: () => storeUnusedHelper() +}), succeed(Other, { + readOther: () => "other", + otherUnused: () => otherUnusedHelper() +})); +const program = gen(function* () { + const store = yield* Store; + const other = yield* Other; + const key = Other; + const context$2 = yield* context(); + return [ + store.readOne(), + other.readOther(), + getOrUndefined(context$2, key).otherUnused() + ]; +}); +assert.deepStrictEqual(await runPromise(provide(program, layer)), [ + "read", + "other", + "otherUnused" +]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/main.js new file mode 100644 index 000000000000..898fc963e8e7 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_unresolved_key/main.js @@ -0,0 +1,27 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A keyed lookup whose key argument is not one declared key: either service may +// be the one looked up, so both keep every method. +const Store = Context.Service("test/RealLookupUnresolvedStore") +const Other = Context.Service("test/RealLookupUnresolvedOther") + +const storeUnusedHelper = () => "storeUnused" +const otherUnusedHelper = () => "otherUnused" + +const layer = Layer.mergeAll( + Layer.succeed(Store, { readOne: () => "read", storeUnused: () => storeUnusedHelper() }), + Layer.succeed(Other, { readOther: () => "other", otherUnused: () => otherUnusedHelper() }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + const other = yield* Other + const key = Number("1") === 1 ? Other : Store + const context = yield* Effect.context() + return [store.readOne(), other.readOther(), Context.getOrUndefined(context, key).otherUnused()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, layer)), ["read", "other", "otherUnused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_update_service_scoped/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_update_service_scoped/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_update_service_scoped/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_update_service_scoped/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_update_service_scoped/artifacts.snap new file mode 100644 index 000000000000..6e55057d878f --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_update_service_scoped/artifacts.snap @@ -0,0 +1,5078 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Effect.updateServiceScoped` looks a service up other than by `yield*` at 25:12 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Type guard that checks whether a value implements the {@link Redactable} +* interface. +* +* **When to use** +* +* Use to narrow an unknown value before calling redaction-specific helpers. +* +* @see {@link Redactable} for the interface being checked +* @see {@link redact} to apply redaction if the value is redactable +* @stability stable +* @category guards +* @since 3.10.0 +*/ +const isRedactable = (u) => hasProperty(u, symbolRedactable); +/** +* Returns a redacted value if it implements {@link Redactable}, otherwise returns it +* unchanged. +* +* **When to use** +* +* Use as the general-purpose entry point for redaction when the input may +* or may not implement the redaction protocol. +* +* **Details** +* +* This function calls {@link isRedactable} and, when it returns `true`, +* delegates to {@link getRedacted}. +* +* **Gotchas** +* +* Redaction is not recursive. Nested redactable values inside the returned +* object are not automatically redacted. +* +* @see {@link isRedactable} to check before redacting +* @see {@link getRedacted} for the lower-level variant for known redactables +* @stability stable +* @category destructors +* @since 3.10.0 +*/ +function redact(u) { + if (isRedactable(u)) return getRedacted(u); + return u; +} +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +/** +* Converts a value to its structured inspection representation. +* +* **When to use** +* +* Use when you need the structured representation of an inspectable value +* without risking unhandled errors. +* +* **Details** +* +* This function applies redaction before extracting data from objects that +* implement `toJSON`, recursively processes arrays, and handles errors +* gracefully. Plain objects are returned unchanged, so the result is not +* guaranteed to be accepted by `JSON.stringify`; it may still contain values +* such as `BigInt`, functions, or circular references. +* +* @see {@link toStringUnknown} for converting unknown values to strings +* +* @stability stable +* @category converting +* @since 4.0.0 +*/ +const toJson = (input) => { + try { + input = redact(input); + if (hasProperty(input, "toJSON") && isFunction(input["toJSON"]) && input["toJSON"].length === 0) return input.toJSON(); + else if (Array.isArray(input)) return input.map(toJson); + return input; + } catch { + return "[toJSON threw]"; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/option.js +/** +* @since 2.0.0 +*/ +const TypeId$3 = "~effect/Option"; +const CommonProto = { + [TypeId$3]: { _A: (_) => _ }, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + } +}; +const SomeProto = /*#__PURE__*/ Object.defineProperty(/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(CommonProto), { + _tag: "Some", + _op: "Some", + [symbol](that) { + return isOption(that) && isSome(that) && equals(this.value, that.value); + }, + [symbol$1]() { + return combine(hash(this._tag))(hash(this.value)); + }, + toString() { + return `some(${format(this.value)})`; + }, + toJSON() { + return { + _id: "Option", + _tag: this._tag, + value: toJson(this.value) + }; + } +}), "valueOrUndefined", { get() { + return this.value; +} }); +const NoneHash = /*#__PURE__*/ hash("None"); +const NoneProto = /*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(CommonProto), { + _tag: "None", + _op: "None", + valueOrUndefined: void 0, + [symbol](that) { + return isOption(that) && isNone$1(that); + }, + [symbol$1]() { + return NoneHash; + }, + toString() { + return `none()`; + }, + toJSON() { + return { + _id: "Option", + _tag: this._tag + }; + } +}); +/** @internal */ +const isOption = (input) => hasProperty(input, TypeId$3); +/** @internal */ +const isNone$1 = (fa) => fa._tag === "None"; +/** @internal */ +const isSome = (fa) => fa._tag === "Some"; +/** @internal */ +const none$1 = /*#__PURE__*/ Object.create(NoneProto); +/** @internal */ +const SomeImpl = function(value) { + this.value = value; +}; +SomeImpl.prototype = SomeProto; +/** @internal */ +const some$1 = (value) => new SomeImpl(value); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Option.js +/** +* Creates an `Option` representing the absence of a value. +* +* **When to use** +* +* Use to represent a missing or uninitialized value, such as returning "no +* result" from a function. +* +* **Details** +* +* - Returns `Option`, which is a subtype of `Option` for any `A` +* - Always returns the same singleton instance +* +* **Example** (Creating an empty Option) +* +* ```ts import.meta.vitest +* import { Option } from "effect" +* +* // ┌─── Option +* // ▼ +* const noValue = Option.none() // => Option.none() +* ``` +* +* @see {@link some} for the opposite operation. +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const none = () => none$1; +/** +* Wraps the given value into an `Option` to represent its presence. +* +* **When to use** +* +* Use to wrap a known present value as `Option` +* - Returning a successful result from a partial function +* +* **Details** +* +* - Always returns `Some` +* - Does not filter `null` or `undefined`; use {@link fromNullishOr} for that +* +* **Example** (Wrapping a value) +* +* ```ts import.meta.vitest +* import { Option } from "effect" +* +* // ┌─── Option +* // ▼ +* const value = Option.some(1) // => Option.some(1) +* ``` +* +* @see {@link none} for the opposite operation. +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const some = some$1; +/** +* Checks whether an `Option` is `None` (absent). +* +* **When to use** +* +* Use when you need to branch on an absent `Option` before accessing `.value`. +* +* **Details** +* +* - Acts as a type guard, narrowing to `None` +* +* **Example** (Checking for None) +* +* ```ts import.meta.vitest +* import { Option } from "effect" +* +* Option.isNone(Option.some(1)) // => false +* Option.isNone(Option.none()) // => true +* ``` +* +* @see {@link isSome} for the opposite check. +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isNone = isNone$1; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets the service for a key, throwing if an absent non-reference key cannot be +* resolved. +* +* **When to use** +* +* Use when you need to read a service from a context whose type does not prove +* the service is present. +* +* **Details** +* +* If the key is a `Context.Reference` and no override is stored in the +* context, its cached default value is returned. For absent non-reference keys, +* this function throws a runtime error. +* +* **Example** (Getting services unsafely) +* +* ```ts import.meta.vitest +* import { Context, Option } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.getUnsafe(context, Port).PORT // => 8080 +* Context.getOption(context, Timeout) // => Option.none() +* ``` +* +* @see {@link get} for type-checked service access +* @see {@link getOption} for optional service access +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const getUnsafe = /*#__PURE__*/ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = getUnsafe; +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Gets the service for a key safely wrapped in an `Option`. +* +* **When to use** +* +* Use when you need to read a `Context` service as an `Option` so absence is +* represented as data. +* +* **Details** +* +* Returns `Option.some` when the service is stored in the context. If the key +* is a `Context.Reference` and no override is stored, returns `Option.some` of +* the cached default value. Missing non-reference keys return `Option.none`. +* +* **Example** (Getting optional services) +* +* ```ts import.meta.vitest +* import { Context, Option } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.getOption(context, Port) // => Option.some({ PORT: 8080 }) +* Context.getOption(context, Timeout) // => Option.none() +* ``` +* +* @see {@link getOrElse} for returning a fallback value directly +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const getOption = /*#__PURE__*/ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value !== notFound) return some(value); + return isReference(service) ? some(getDefaultValue(service)) : none(); +}); +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const updateServiceScoped$1 = (service, update, options) => uninterruptible(withFiber((fiber) => { + const original = getUnsafe(fiber.context, service); + const updated = update(original); + fiber.setContext(add(fiber.context, service, updated)); + return scopeAddFinalizerExit(getUnsafe(fiber.context, scopeTag), (_) => { + const currentOption = getOption(fiber.context, service); + if (isNone(currentOption)) return void_; + const current = currentOption.value; + let next; + if (options?.reset === void 0) { + if (current !== updated) return void_; + next = original; + } else next = options.reset(original, updated, current); + fiber.setContext(add(fiber.context, service, next)); + return void_; + }); +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerExit = (scope, finalizer) => { + return suspend(() => { + if (scope.state._tag === "Closed") return finalizer(scope.state.exit); + scopeAddFinalizerUnsafe(scope, {}, finalizer); + return void_; + }); +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scoped$1 = (self) => withFiber((fiber) => { + const prev = fiber.context; + const scope = scopeMakeUnsafe(); + fiber.setContext(add(fiber.context, scopeTag, scope)); + onExitUnsafe(fiber, (exit) => { + fiber.setContext(prev); + return scopeCloseUnsafe(scope, exit); + }); + return self; +}); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Updates a service for the lifetime of the current scope and restores its +* previous value when the scope closes. +* +* **When to use** +* +* Use when you need a setup effect to change a service for subsequent effects +* in the same scope. +* +* **Details** +* +* The updater receives the currently visible service value. A +* `Context.Service` remains in the requirements, while a `Context.Reference` +* uses its default when no override is present and adds no service requirement. +* The returned effect always requires `Scope`. The optional `reset` function +* receives the original, updated, and current values when the scope closes, +* allowing changes to be merged during restoration. It defaults to returning +* the original value. +* +* **Example** (Updating a reference within a scope) +* +* ```ts import.meta.vitest +* import { Context, Effect } from "effect" +* const output: Array = [] +* +* const CurrentNumber = Context.Reference("CurrentNumber", { +* defaultValue: () => 1 +* }) +* +* const program = Effect.gen(function*() { +* const before = yield* CurrentNumber +* const during = yield* Effect.scoped( +* Effect.gen(function*() { +* yield* Effect.updateServiceScoped( +* CurrentNumber, +* (value) => value + 1, +* { +* // Optional: when omitted, the original value is restored +* reset: (original, updated, current) => +* Math.max(original, updated, current) + 1 +* } +* ) +* return yield* CurrentNumber +* }) +* ) +* const after = yield* CurrentNumber +* +* void output.push([before, during, after]) +* }) +* +* await Effect.runPromise(program) +* output // => [[1, 2, 3]] +* ``` +* +* @see {@link updateService} for updating a service only within a wrapped effect +* +* @stability stable +* @category providing services +* @since 4.0.0 +*/ +const updateServiceScoped = updateServiceScoped$1; +/** +* Runs an effect with a scope that closes when the effect completes. +* +* **When to use** +* +* Use to acquire scoped resources for the duration of a single workflow. +* +* **Details** +* +* Finalizers for resources acquired inside the workflow run as soon as the +* workflow completes, whether by success, failure, or interruption. +* +* **Example** (Running a scoped acquisition) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* const resource = Effect.acquireRelease( +* Effect.sync(() => { output.push("Acquiring resource") }).pipe(Effect.as("resource")), +* () => Effect.sync(() => { output.push("Releasing resource") }) +* ) +* +* const program = Effect.scoped( +* Effect.gen(function*() { +* const res = yield* resource +* yield* Effect.sync(() => { output.push(`Using ${res}`) }) +* return res +* }) +* ) +* +* Effect.runSync(program) +* output // => ["Acquiring resource", "Using resource", "Releasing resource"] +* ``` +* +* @stability stable +* @category resource management +* @since 2.0.0 +*/ +const scoped = scoped$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealUpdateServiceScoped"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const program = scoped(gen(function* () { + const store = yield* Store; + let observed; + yield* updateServiceScoped({ key: "test/RealUpdateServiceScoped" }, (old) => { + observed = old.unused(); + return old; + }); + return [store.readOne(), observed]; +})); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "unused"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_update_service_scoped/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_update_service_scoped/main.js new file mode 100644 index 000000000000..28907957f582 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/lookup_update_service_scoped/main.js @@ -0,0 +1,33 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// `Effect.updateServiceScoped` is a keyed lookup like `updateService`: here by a +// hand-made key, and the callback calls the otherwise-unused method. +const Store = Context.Service("test/RealUpdateServiceScoped") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const program = Effect.scoped( + Effect.gen(function* () { + const store = yield* Store + let observed + yield* Effect.updateServiceScoped({ key: "test/RealUpdateServiceScoped" }, (old) => { + observed = old.unused() + return old + }) + return [store.readOne(), observed] + }) +) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "unused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/node_prefixed_vm/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/node_prefixed_vm/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/node_prefixed_vm/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/node_prefixed_vm/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/node_prefixed_vm/artifacts.snap new file mode 100644 index 000000000000..b2014e5039fa --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/node_prefixed_vm/artifacts.snap @@ -0,0 +1,4685 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] host operation that loads code at 21:3 in main.js + +``` + +## UNRESOLVED_IMPORT + +```text +[UNRESOLVED_IMPORT] Could not resolve 'node:vm' in main.js + ╭─[ main.js:5:33 ] + │ + 5 │ import { compileFunction } from "node:vm" + │ ────┬──── + │ ╰────── Module not found, treating it as an external dependency +───╯ + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +import { compileFunction } from "node:vm"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber$1 = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber$1((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber$1((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber$1((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber$1((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber$1((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber$1((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber$1((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Creates an `Effect` that always succeeds with a given value. +* +* **When to use** +* +* Use when an effect should complete successfully with a specific value without any errors +* or external dependencies. +* +* **Example** (Creating a successful effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* // Creating an effect that represents a successful scenario +* // +* // ┌─── Effect +* // ▼ +* const success = Effect.succeed(42) +* Effect.runSync(success) // => 42 +* ``` +* +* @see {@link fail} to create an effect that represents a failure. +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = succeed$1; +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides access to the current fiber within an effect computation. +* +* **Example** (Reading the current fiber) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const program = Effect.withFiber((fiber) => Effect.succeed(typeof fiber.id)) +* +* Effect.runSync(program) // => "number" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const withFiber = withFiber$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealNodeVm"); +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => "unused"; + return Store.of({ + readOne, + unused + }); +})); +const observe = (context) => compileFunction("return ctx.mapUnsafe.get(\"test/RealNodeVm\").unused()", ["ctx"])(context); +const program = gen(function* () { + const store = yield* Store; + const context = yield* withFiber((fiber) => succeed(fiber.context)); + return [store.readOne(), observe(context)]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "unused"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/node_prefixed_vm/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/node_prefixed_vm/main.js new file mode 100644 index 000000000000..441055171665 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/node_prefixed_vm/main.js @@ -0,0 +1,30 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import { compileFunction } from "node:vm" + +// Review finding: `node:vm` runs code outside the module graph, like `vm`. +// Every method of the service must be kept. +const Store = Context.Service("test/RealNodeVm") + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => "unused" + return Store.of({ readOne, unused }) + }) +) + +const observe = (context) => + compileFunction('return ctx.mapUnsafe.get("test/RealNodeVm").unused()', ["ctx"])(context) + +const program = Effect.gen(function* () { + const store = yield* Store + // The live Context of the provided scope, through the running Fiber. + const context = yield* Effect.withFiber((fiber) => Effect.succeed(fiber.context)) + return [store.readOne(), observe(context)] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "unused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/_test.mjs new file mode 100644 index 000000000000..a698a820f53d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/_test.mjs @@ -0,0 +1,15 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["readHelper", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/artifacts.snap new file mode 100644 index 000000000000..414445ee269f --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/artifacts.snap @@ -0,0 +1,4612 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealJsonClean"); +const readHelper = () => "read"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + return Store.of({ readOne }); +})); +const settings = { mode: "fast" }; +const program = gen(function* () { + return [(yield* Store).readOne(), JSON.stringify({ a: [settings, { n: 1 }] })]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "{\"a\":[{\"mode\":\"fast\"},{\"n\":1}]}"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/main.js new file mode 100644 index 000000000000..c1cae4c6531d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_json_clean/main.js @@ -0,0 +1,27 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Positive gate: JSON.stringify of nested user data that holds no Effect runtime +// object. The pass must still remove `writeOne`. +const Store = Context.Service("test/RealJsonClean") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +const settings = { mode: "fast" } +const program = Effect.gen(function* () { + return [(yield* Store).readOne(), JSON.stringify({ a: [settings, { n: 1 }] })] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", '{"a":[{"mode":"fast"},{"n":1}]}']) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/_test.mjs new file mode 100644 index 000000000000..a698a820f53d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/_test.mjs @@ -0,0 +1,15 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["readHelper", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/artifacts.snap new file mode 100644 index 000000000000..149c4311544c --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/artifacts.snap @@ -0,0 +1,5218 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `string`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* string. +* +* **Details** +* +* Uses `typeof input === "string"`. +* +* **Example** (Guarding strings) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = "hi" +* +* if (Predicate.isString(data)) { +* data.toUpperCase() // => "HI" +* } +* ``` +* +* @see {@link isNumber} +* @see {@link isBoolean} +* @see {@link Refinement} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isString(input) { + return typeof input === "string"; +} +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +/** +* Checks whether a value is iterable. +* +* **When to use** +* +* Use when you need a `Predicate` guard before iterating an unknown value. +* +* **Details** +* +* Accepts strings as iterable and uses `hasProperty` for `Symbol.iterator`. +* +* **Example** (Guarding iterables) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = [1, 2, 3] +* +* Predicate.isIterable(data) // => true +* ``` +* +* @see {@link isSet} +* @see {@link isMap} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isIterable(input) { + return hasProperty(input, Symbol.iterator) || isString(input); +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Type guard that checks whether a value implements the {@link Redactable} +* interface. +* +* **When to use** +* +* Use to narrow an unknown value before calling redaction-specific helpers. +* +* @see {@link Redactable} for the interface being checked +* @see {@link redact} to apply redaction if the value is redactable +* @stability stable +* @category guards +* @since 3.10.0 +*/ +const isRedactable = (u) => hasProperty(u, symbolRedactable); +/** +* Returns a redacted value if it implements {@link Redactable}, otherwise returns it +* unchanged. +* +* **When to use** +* +* Use as the general-purpose entry point for redaction when the input may +* or may not implement the redaction protocol. +* +* **Details** +* +* This function calls {@link isRedactable} and, when it returns `true`, +* delegates to {@link getRedacted}. +* +* **Gotchas** +* +* Redaction is not recursive. Nested redactable values inside the returned +* object are not automatically redacted. +* +* @see {@link isRedactable} to check before redacting +* @see {@link getRedacted} for the lower-level variant for known redactables +* @stability stable +* @category destructors +* @since 3.10.0 +*/ +function redact(u) { + if (isRedactable(u)) return getRedacted(u); + return u; +} +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +/** +* Converts a value to its structured inspection representation. +* +* **When to use** +* +* Use when you need the structured representation of an inspectable value +* without risking unhandled errors. +* +* **Details** +* +* This function applies redaction before extracting data from objects that +* implement `toJSON`, recursively processes arrays, and handles errors +* gracefully. Plain objects are returned unchanged, so the result is not +* guaranteed to be accepted by `JSON.stringify`; it may still contain values +* such as `BigInt`, functions, or circular references. +* +* @see {@link toStringUnknown} for converting unknown values to strings +* +* @stability stable +* @category converting +* @since 4.0.0 +*/ +const toJson = (input) => { + try { + input = redact(input); + if (hasProperty(input, "toJSON") && isFunction(input["toJSON"]) && input["toJSON"].length === 0) return input.toJSON(); + else if (Array.isArray(input)) return input.map(toJson); + return input; + } catch { + return "[toJSON threw]"; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/result.js +const TypeId$3 = "~effect/Result"; +const CommonProto = { + [TypeId$3]: { + /* v8 ignore next 2 */ + _A: (_) => _, + _E: (_) => _ + }, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + } +}; +const SuccessProto = /*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(CommonProto), { + _tag: "Success", + _op: "Success", + [symbol](that) { + return isResult(that) && isSuccess(that) && equals(this.success, that.success); + }, + [symbol$1]() { + return combine(hash(this._tag))(hash(this.success)); + }, + toString() { + return `success(${format(this.success)})`; + }, + toJSON() { + return { + _id: "Result", + _tag: this._tag, + value: toJson(this.success) + }; + } +}); +const FailureProto = /*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(CommonProto), { + _tag: "Failure", + _op: "Failure", + [symbol](that) { + return isResult(that) && isFailure$1(that) && equals(this.failure, that.failure); + }, + [symbol$1]() { + return combine(hash(this._tag))(hash(this.failure)); + }, + toString() { + return `failure(${format(this.failure)})`; + }, + toJSON() { + return { + _id: "Result", + _tag: this._tag, + failure: toJson(this.failure) + }; + } +}); +/** @internal */ +const isResult = (input) => hasProperty(input, TypeId$3); +/** @internal */ +const isFailure$1 = (result) => result._tag === "Failure"; +/** @internal */ +const isSuccess = (result) => result._tag === "Success"; +/** @internal */ +const FailureImpl = function(failure) { + this.failure = failure; +}; +FailureImpl.prototype = FailureProto; +/** @internal */ +const fail$1 = (failure) => new FailureImpl(failure); +/** @internal */ +const SuccessImpl = function(success) { + this.success = success; +}; +SuccessImpl.prototype = SuccessProto; +/** @internal */ +const succeed$3 = (success) => new SuccessImpl(success); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Result.js +/** +* Creates a `Result` holding a `Success` value. +* +* **Details** +* +* - Use when you have a value and want to lift it into the `Result` type +* - The error type `E` defaults to `never` +* +* **Example** (Wrapping a value) +* +* ```ts import.meta.vitest +* import { Result } from "effect" +* +* Result.succeed(42) // => Result.succeed(42) +* ``` +* +* @see {@link fail} to create a Failure +* @see {@link void_ void} for a pre-built `Success` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const succeed$2 = succeed$3; +/** +* Creates a `Result` holding a `Failure` value. +* +* **When to use** +* +* Use to represent a failed `Result` with a typed failure value. +* +* **Details** +* +* - The success type `A` defaults to `never` +* +* **Example** (Creating a failure) +* +* ```ts import.meta.vitest +* import { Result } from "effect" +* +* Result.fail("Something went wrong") // => Result.fail("Something went wrong") +* ``` +* +* @see {@link succeed} to create a Success +* @see {@link mapError} to transform the error +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fail = fail$1; +/** +* Checks whether a `Result` is a `Failure`. +* +* **When to use** +* +* Use to narrow a known `Result` to the `Failure` variant. +* +* **Details** +* +* - Acts as a TypeScript type guard, narrowing to `Failure` +* - After narrowing, you can access `.failure` to read the error value +* +* **Example** (Narrowing to failure) +* +* ```ts import.meta.vitest +* import { Result } from "effect" +* +* const result = Result.fail("oops") +* +* if (Result.isFailure(result)) { +* result.failure // => "oops" +* } +* ``` +* +* @see {@link isSuccess} for the opposite check +* @see {@link isResult} to check if a value is any Result +* +* @stability stable +* @category guards +* @since 4.0.0 +*/ +const isFailure = isFailure$1; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const findError = (self) => { + for (let i = 0; i < self.reasons.length; i++) { + const reason = self.reasons[i]; + if (reason._tag === "Fail") return succeed$2(reason.error); + } + return fail(self); +}; +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** +* Selects the first typed error unless a defect is present, in which case +* every `Fail` is elected to `Die`. Interrupts do not block typed recovery. +* +* @internal +*/ +const findRecoverableError = (self) => hasDies(self) ? fail(causeElectDefects(self)) : findError(self); +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +const fiberInterruptChildren = (fiber) => { + if (fiber._children === void 0 || fiber._children.size === 0) return; + return fiberInterruptAll(fiber._children); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberJoin = (self) => { + const impl = self; + if (impl._exit) return impl._exit; + return callback((resume) => { + if (impl._exit) return resume(impl._exit); + return sync(self.addObserver(resume)); + }); +}; +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +/** @internal */ +const result = (self) => matchEager(self, { + onFailure: fail, + onSuccess: succeed$2 +}); +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +const matchSuccess = function(value, fiber) { + const handlers = this.payload; + return fiber.succeedWith(continuationMarksStack ? handlers.onSuccess(value) : internalCall(() => handlers.onSuccess(value))); +}; +const makeMatch = (op, onFailure) => { + const Proto = makePrimitiveProto({ + op, + [evaluate]: evaluateCont, + [contA]: matchSuccess, + [contE]: onFailure + }); + const MatchImpl = function(self, handlers) { + this[args] = self; + this.payload = handlers; + }; + MatchImpl.prototype = Proto; + return MatchImpl; +}; +const MatchImpl = /*#__PURE__*/ makeMatch("Match", function(cause, fiber) { + const error = findRecoverableError(cause); + if (isFailure(error)) return failCause(error.failure); + const handlers = this.payload; + return fiber.succeedWith(continuationMarksStack ? handlers.onFailure(error.success) : internalCall(() => handlers.onFailure(error.success))); +}); +/** @internal */ +const match = /*#__PURE__*/ dual(2, (self, options) => new MatchImpl(self, options)); +/** @internal */ +const matchEager = /*#__PURE__*/ dual(2, (self, options) => { + if (effectIsExit(self)) { + if (self._tag === "Success") return exitSucceed(options.onSuccess(self.value)); + const error = findRecoverableError(self.cause); + if (isFailure(error)) return exitFailCause(error.failure); + return exitSucceed(options.onFailure(error.success)); + } + return match(self, options); +}); +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const all$1 = (arg, options) => { + if (isIterable(arg)) return options?.mode === "result" ? forEach(arg, result, options) : forEach(arg, identity, options); + else if (options?.discard) return options.mode === "result" ? forEach(Object.values(arg), result, options) : forEach(Object.values(arg), identity, options); + return suspend(() => map(forEach(Object.entries(arg), ([key, effect]) => map(options?.mode === "result" ? result(effect) : effect, (value) => [key, value]), { concurrency: options?.concurrency }), Object.fromEntries)); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkChild$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, options) => withFiber((fiber) => { + interruptChildrenPatch(); + return succeed$1(forkUnsafe$1(fiber, self, options?.startImmediately, false, options?.uninterruptible ?? false)); +})); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +/** @internal */ +function interruptChildrenPatch() { + fiberMiddleware.interruptChildren ??= fiberInterruptChildren; +} +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Combines an iterable or record of effects into one effect whose success shape +* follows the input. +* +* **When to use** +* +* Use to run a known collection of effects and collect results in the same +* tuple, iterable, or record shape. +* +* **Details** +* +* Tuple and iterable inputs collect results in order. Record inputs collect +* results under the same keys. By default, the combined effect fails on the +* first failure; with concurrent execution, effects that have already started +* may be interrupted, while effects not yet started are skipped. +* +* Options: +* +* Use `concurrency` to control sequential or concurrent execution. Use +* `mode: "result"` to run every effect and collect each success or failure as a +* `Result` in the same output shape. Use `discard: true` to ignore successful +* values and return `void`. +* +* **Example** (Collecting tuple results in order) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const tupleOfEffects = [ +* Effect.succeed(42), +* Effect.succeed("Hello") +* ] as const +* +* // ┌─── Effect<[number, string], never, never> +* // ▼ +* const resultsAsTuple = Effect.all(tupleOfEffects) +* +* await Effect.runPromise(resultsAsTuple) // => [42, "Hello"] +* ``` +* +* **Example** (Collecting iterable results in order) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const iterableOfEffects: Iterable> = [1, 2, 3].map( +* Effect.succeed +* ) +* +* // ┌─── Effect +* // ▼ +* const resultsAsArray = Effect.all(iterableOfEffects) +* +* await Effect.runPromise(resultsAsArray) // => [1, 2, 3] +* ``` +* +* **Example** (Collecting struct results by key) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const structOfEffects = { +* a: Effect.succeed(42), +* b: Effect.succeed("Hello") +* } +* +* // ┌─── Effect<{ a: number; b: string; }, never, never> +* // ▼ +* const resultsAsStruct = Effect.all(structOfEffects) +* +* await Effect.runPromise(resultsAsStruct) // => { a: 42, b: "Hello" } +* ``` +* +* **Example** (Collecting record results by key) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const recordOfEffects: Record> = { +* key1: Effect.succeed(1), +* key2: Effect.succeed(2) +* } +* +* // ┌─── Effect<{ [x: string]: number; }, never, never> +* // ▼ +* const resultsAsRecord = Effect.all(recordOfEffects) +* +* await Effect.runPromise(resultsAsRecord) // => { key1: 1, key2: 2 } +* ``` +* +* **Example** (Stopping on the first failure) +* +* ```ts import.meta.vitest +* import { Effect, Exit } from "effect" +* const output: Array = [] +* const record = (value: unknown) => Effect.sync(() => { output.push(value) }) +* +* const program = Effect.all([ +* Effect.succeed("Task1").pipe(Effect.tap(record)), +* Effect.fail("Task2: Oh no!").pipe(Effect.tap(record)), +* // Won't execute due to earlier failure +* Effect.succeed("Task3").pipe(Effect.tap(record)) +* ]) +* +* const outcome = await Effect.runPromiseExit(program) +* const observation = [output, outcome] // => [["Task1"], Exit.fail("Task2: Oh no!")] +* ``` +* +* @see {@link forEach} for iterating over elements and applying an effect. +* @stability stable +* @category collecting +* @since 2.0.0 +*/ +const all = all$1; +/** +* Creates an `Effect` that always succeeds with a given value. +* +* **When to use** +* +* Use when an effect should complete successfully with a specific value without any errors +* or external dependencies. +* +* **Example** (Creating a successful effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* // Creating an effect that represents a successful scenario +* // +* // ┌─── Effect +* // ▼ +* const success = Effect.succeed(42) +* Effect.runSync(success) // => 42 +* ``` +* +* @see {@link fail} to create an effect that represents a failure. +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = succeed$1; +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Returns an effect that forks this effect into its own separate fiber, +* returning the fiber immediately, without waiting for it to begin executing +* the effect. +* +* **Details** +* +* You can use the `forkChild` method whenever you want to execute an effect in a +* new fiber, concurrently and without "blocking" the fiber executing other +* effects. Using fibers can be tricky, so instead of using this method +* directly, consider higher-level methods such as `Effect.race`, +* `Effect.raceFirst`, or `Effect.all` with a concurrency option. +* +* The fiber returned by this method has methods to interrupt the fiber and to +* wait for it to finish executing the effect. See `Fiber` for more +* information. +* +* Whenever you use this method to launch a new fiber, the new fiber is +* attached to the parent fiber's scope. This means when the parent fiber +* terminates, the child fiber will be terminated as well, ensuring that no +* fibers leak. This behavior is called "auto supervision", and if this +* behavior is not desired, you may use the `forkDetach` or `forkIn` methods. +* +* **Example** (Forking a child fiber) +* +* ```ts import.meta.vitest +* import { Effect, Fiber } from "effect" +* +* const task = Effect.succeed("result") +* +* const program = Effect.gen(function*() { +* const fiber = yield* task.pipe(Effect.forkChild) +* const result = yield* Fiber.join(fiber) +* return result +* }) +* +* await Effect.runPromise(program) // => "result" +* ``` +* +* @stability stable +* @category forking +* @since 4.0.0 +*/ +const forkChild = forkChild$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Fiber.js +/** +* Joins a fiber, blocking until it completes. If the fiber succeeds, +* returns its value. If it fails, the error is propagated. +* +* **When to use** +* +* Use when you need a forked fiber's failure to fail the current Effect because +* that fiber is part of the current workflow. +* +* **Gotchas** +* +* Joining a failed fiber propagates the fiber's Cause. Use {@link await_ await} when +* you need to inspect the `Exit` instead of failing. +* +* **Example** (Joining a fiber) +* +* ```ts import.meta.vitest +* import { Effect, Fiber } from "effect" +* +* const program = Effect.gen(function*() { +* const fiber = yield* Effect.forkChild(Effect.succeed(42)) +* return yield* Fiber.join(fiber) +* }) +* +* const actual = await Effect.runPromise(program) +* actual // => 42 +* ``` +* +* @see {@link await_ await} for inspecting the fiber outcome as an Exit +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const join = fiberJoin; +// main.js +const Store = Service("test/RealNumericIndex"); +const readHelper = () => "read"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + return Store.of({ readOne }); +})); +const program = gen(function* () { + const fibers = yield* all([forkChild(gen(function* () { + return (yield* Store).readOne(); + })), forkChild(succeed("two"))]); + const results = []; + for (let i = 0; i < fibers.length; i++) results.push(yield* join(fibers[i])); + return results; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "two"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/main.js new file mode 100644 index 000000000000..d1b0b53887cd --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_numeric_index/main.js @@ -0,0 +1,35 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Positive gate: Fibers indexed by a counted loop variable. A numeric index cannot +// name a Context internal, so the pass must still remove `writeOne`. +const Store = Context.Service("test/RealNumericIndex") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +import * as Fiber from "effect/Fiber" +const program = Effect.gen(function* () { + const fibers = yield* Effect.all([ + Effect.forkChild(Effect.gen(function* () { return (yield* Store).readOne() })), + Effect.forkChild(Effect.succeed("two")) + ]) + const results = [] + for (let i = 0; i < fibers.length; i++) { + results.push(yield* Fiber.join(fibers[i])) + } + return results +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "two"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/_test.mjs new file mode 100644 index 000000000000..a698a820f53d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/_test.mjs @@ -0,0 +1,15 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["readHelper", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/artifacts.snap new file mode 100644 index 000000000000..f0ae05643557 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/artifacts.snap @@ -0,0 +1,4693 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map$1 = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map$1(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map$1(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map$1((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Transforms the value inside an effect by applying a function to it. +* +* **When to use** +* +* Use to transform an effect's success value with a function that returns a +* plain value, producing a new effect without changing the original effect's +* typed error or context requirements. +* +* **Details** +* +* `map` takes a function and applies it to the value contained within an +* effect, creating a new effect with the transformed value. +* +* It's important to note that effects are immutable, meaning that the original +* effect is not modified. Instead, a new effect is returned with the updated +* value. +* +* **Example** (Choosing map syntax variants) +* +* ```ts import.meta.vitest +* import { Effect, pipe } from "effect" +* const output: Array = [] +* +* const myEffect = Effect.succeed(1) +* const transformation = (n: number) => n + 1 +* +* const mappedWithPipe = pipe(myEffect, Effect.map(transformation)) +* const mappedWithDataFirst = Effect.map(myEffect, transformation) +* const mappedWithMethod = myEffect.pipe(Effect.map(transformation)) +* +* void output.push(Effect.runSync(Effect.all([ +* mappedWithPipe, +* mappedWithDataFirst, +* mappedWithMethod +* ]))) +* output // => [[2, 2, 2]] +* ``` +* +* **Example** (Adding a service charge) +* +* ```ts import.meta.vitest +* import { Effect, pipe } from "effect" +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const finalAmount = pipe( +* fetchTransactionAmount, +* Effect.map(addServiceCharge) +* ) +* +* await Effect.runPromise(finalAmount) // => 101 +* ``` +* +* @see {@link mapError} for a version that operates on the error channel. +* @see {@link mapBoth} for a version that operates on both channels. +* @see {@link flatMap} or {@link andThen} for a version that can return a new effect. +* @stability stable +* @category mapping +* @since 2.0.0 +*/ +const map = map$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealSuccessChannel"); +const readHelper = () => "read"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + return Store.of({ readOne }); +})); +const load = gen(function* () { + return JSON.parse("{\"mode\":\"fast\",\"level\":2}"); +}); +const program = gen(function* () { + const store = yield* Store; + const settings = yield* map(load, (parsed) => ({ + ...parsed, + extra: true + })); + const values = []; + for (const name in settings) values.push(String(settings[name])); + return [ + store.readOne(), + Object.keys(settings).join(","), + values.join(",") + ]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), [ + "read", + "mode,level,extra", + "fast,2,true" +]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/main.js new file mode 100644 index 000000000000..23b29e36e893 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provenance_success_channel/main.js @@ -0,0 +1,33 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Positive gate: data parsed with JSON.parse inside Effect.gen, passed through +// Effect.map and `yield*`, is user data. Enumerating it must not keep `writeOne`. +const Store = Context.Service("test/RealSuccessChannel") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +const load = Effect.gen(function* () { + return JSON.parse('{"mode":"fast","level":2}') +}) +const program = Effect.gen(function* () { + const store = yield* Store + const settings = yield* Effect.map(load, (parsed) => ({ ...parsed, extra: true })) + const values = [] + for (const name in settings) values.push(String(settings[name])) + return [store.readOne(), Object.keys(settings).join(","), values.join(",")] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "mode,level,extra", "fast,2,true"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/_test.mjs new file mode 100644 index 000000000000..05e0682e28b9 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/artifacts.snap new file mode 100644 index 000000000000..9fa71a2f59b4 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/artifacts.snap @@ -0,0 +1,4716 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make$1(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make$1 = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make$1(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced$1 = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced$1(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make$1(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +/** +* Creates an Effect-returning function without tracing. +* +* **When to use** +* +* Use when you are defining a reusable Effect function whose implementation +* would otherwise be a normal function returning {@link gen}, especially when +* tracing spans or stack-frame capture are not needed. +* +* **Details** +* +* Compared to a plain function that returns {@link gen}, `Effect.fnUntraced` +* reuses the generator body instead of allocating a fresh generator closure +* around the arguments on every call. It does not record an Effect stack-frame +* boundary and does not create tracing spans. Use {@link fn} when you need +* those stack frames or spans. Additional arguments after the generator body +* act like `pipe` transforms: each transform receives the previous result and +* the original function arguments. Generator bodies may declare a `this` +* parameter; pass `{ self }` before the body to bind `this` when the function +* is created. Annotate the generator return type with +* `Effect.fn.Return` when the produced `Effect` type needs to be +* stated explicitly. +* +* **Example** (Defining untraced effect functions) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ) { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Transforming the returned Effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced( +* function*(value: string) { +* return yield* Effect.succeed(value.length) +* }, +* (effect, value) => +* effect.pipe(Effect.map((length) => `${value}: ${length}`)) +* ) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello: 5" +* ``` +* +* **Example** (Annotating an untraced non-parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ): Effect.fn.Return { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Annotating an untraced parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: A +* ): Effect.fn.Return { +* return yield* Effect.succeed(value) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello" +* ``` +* +* @stability stable +* @category constructors +* @since 3.12.0 +*/ +const fnUntraced = fnUntraced$1; +// main.js +const Store = Service("test/RealProviderBuilderNamedEscape"); +let exposed; +const build = function inner() { + exposed = inner; + return { + readOne: () => "read", + unused: () => "unused" + }; +}; +const StoreLayer = effect(Store, fnUntraced(function* () { + return build(); +})()); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +assert.strictEqual(await runPromise(provide(program, StoreLayer)), "read"); +assert.strictEqual(exposed().unused(), "unused"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/main.js new file mode 100644 index 000000000000..5e5ce80caee2 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_builder_named_escape/main.js @@ -0,0 +1,27 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A named function expression builder exposes itself through its inner name, +// so another caller gets an object from the same literal. +const Store = Context.Service("test/RealProviderBuilderNamedEscape") + +let exposed +const build = function inner() { + exposed = inner + return { readOne: () => "read", unused: () => "unused" } +} + +const make = Effect.fnUntraced(function* () { + return build() +}) + +const StoreLayer = Layer.effect(Store, make()) + +const program = Effect.gen(function* () { + return (yield* Store).readOne() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), "read") +assert.strictEqual(exposed().unused(), "unused") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/_test.mjs new file mode 100644 index 000000000000..b4e64429cb12 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/_test.mjs @@ -0,0 +1,11 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/artifacts.snap new file mode 100644 index 000000000000..c351a5d5099a --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/artifacts.snap @@ -0,0 +1,4967 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make$1(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make$1 = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets the service for a key, throwing if an absent non-reference key cannot be +* resolved. +* +* **When to use** +* +* Use when you need to read a service from a context whose type does not prove +* the service is present. +* +* **Details** +* +* If the key is a `Context.Reference` and no override is stored in the +* context, its cached default value is returned. For absent non-reference keys, +* this function throws a runtime error. +* +* **Example** (Getting services unsafely) +* +* ```ts import.meta.vitest +* import { Context, Option } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.getUnsafe(context, Port).PORT // => 8080 +* Context.getOption(context, Timeout) // => Option.none() +* ``` +* +* @see {@link get} for type-checked service access +* @see {@link getOption} for optional service access +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const getUnsafe = /*#__PURE__*/ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = getUnsafe; +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make$1(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced$1 = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const updateService$1 = /*#__PURE__*/ dual(3, (self, service, f) => updateContext(self, (s) => { + const prev = getUnsafe(s, service); + const next = f(prev); + if (prev === next) return s; + return add(s, service, next); +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced$1(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$3 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make$1(arguments[0], resource)); + return succeedContext(make$1(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make$1(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$3(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +const provideWith = (self, that, f) => fromBuildMemo((memoMap, scope) => flatMap(Array.isArray(that) ? mergeAllEffect(that, memoMap, scope) : that.build(memoMap, scope), (context) => self.build(memoMap, scope).pipe(provideContext(context), map((merged) => f(merged, context))))); +/** +* Feeds the output services of the dependency layer into the requirements of +* this layer, returning a layer that only provides the services from this layer. +* +* **When to use** +* +* Use when you need to hide an implementation dependency layer from callers. +* +* **Details** +* +* In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is +* built first and is used to satisfy the requirements of `serviceLayer`. +* +* **Example** (Providing layer dependencies) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class UserService extends Context.Service Effect.Effect<{ +* id: string +* name: string +* }> +* }>()("UserService") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* // Create dependency layers +* const databaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) +* }) +* +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(`[LOG] ${msg}`))) +* }) +* +* // UserService depends on Database and Logger +* const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { +* const database = yield* Database +* const logger = yield* Logger +* +* return { +* getUser: Effect.fn("UserService.getUser")(function*(id: string) { +* yield* logger.log(`Looking up user ${id}`) +* const result = yield* database.query( +* `SELECT * FROM users WHERE id = ${id}` +* ) +* return { id, name: result } +* }) +* } +* })) +* +* // Provide dependencies to UserService layer +* const userServiceWithDependencies = userServiceLayer.pipe( +* Layer.provide(Layer.mergeAll(databaseLayer, loggerLayer)) +* ) +* +* // Now UserService layer has no dependencies +* const program = Effect.gen(function*() { +* const userService = yield* UserService +* return yield* userService.getUser("123") +* }).pipe( +* Effect.provide(userServiceWithDependencies) +* ) +* Effect.runSync(program) // => { id: "123", name: "DB: SELECT * FROM users WHERE id = 123" } +* logs // => ["[LOG] Looking up user 123"] +* ``` +* +* @see {@link provideMerge} for retaining the dependency services +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide$2 = /*#__PURE__*/ dual(2, (self, that) => provideWith(self, that, identity)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Runs an effect with a service implementation transformed by the provided +* function. +* +* **Details** +* +* The service must be available in the effect's context; `updateService` +* replaces it for the wrapped effect with the value returned by the updater. +* +* **Example** (Replacing a service for one effect) +* +* ```ts import.meta.vitest +* import { Context, Effect } from "effect" +* const output: Array = [] +* +* // Define a counter service +* const Counter = Context.Service<{ count: number }>("Counter") +* +* const program = Effect.gen(function*() { +* const updatedCounter = yield* Effect.service(Counter) +* yield* Effect.sync(() => { output.push(`Updated count: ${updatedCounter.count}`) }) +* return updatedCounter.count +* }).pipe( +* Effect.updateService(Counter, (counter) => ({ count: counter.count + 1 })) +* ) +* +* // Provide initial service and run +* const result = Effect.provideService(program, Counter, { count: 0 }) +* void output.push(Effect.runSync(result)) +* output // => ["Updated count: 1", 1] +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const updateService = updateService$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +/** +* Creates an Effect-returning function without tracing. +* +* **When to use** +* +* Use when you are defining a reusable Effect function whose implementation +* would otherwise be a normal function returning {@link gen}, especially when +* tracing spans or stack-frame capture are not needed. +* +* **Details** +* +* Compared to a plain function that returns {@link gen}, `Effect.fnUntraced` +* reuses the generator body instead of allocating a fresh generator closure +* around the arguments on every call. It does not record an Effect stack-frame +* boundary and does not create tracing spans. Use {@link fn} when you need +* those stack frames or spans. Additional arguments after the generator body +* act like `pipe` transforms: each transform receives the previous result and +* the original function arguments. Generator bodies may declare a `this` +* parameter; pass `{ self }` before the body to bind `this` when the function +* is created. Annotate the generator return type with +* `Effect.fn.Return` when the produced `Effect` type needs to be +* stated explicitly. +* +* **Example** (Defining untraced effect functions) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ) { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Transforming the returned Effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced( +* function*(value: string) { +* return yield* Effect.succeed(value.length) +* }, +* (effect, value) => +* effect.pipe(Effect.map((length) => `${value}: ${length}`)) +* ) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello: 5" +* ``` +* +* **Example** (Annotating an untraced non-parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ): Effect.fn.Return { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Annotating an untraced parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: A +* ): Effect.fn.Return { +* return yield* Effect.succeed(value) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello" +* ``` +* +* @stability stable +* @category constructors +* @since 3.12.0 +*/ +const fnUntraced = fnUntraced$1; +// client.js +const build = (http) => ({ get: (path) => http.request(path) }); +// main.js +var Client = class extends Service()("test/RealProviderConstructorClient") {}; +var Http = class extends Service()("test/RealProviderConstructorHttp") {}; +const log = []; +const make = fnUntraced(function* (options) { + const http = yield* Http; + log.push(`make ${options.base}`); + return build({ request: (path) => http.request(`${options.base}${path}`) }); +}, updateService(Http, (http) => { + log.push("piped"); + return http; +})); +const HttpLayer = succeed(Http, { request: (url) => `GET ${url}` }); +const ClientLayer = effect(Client, make({ base: "mock:" })).pipe(provide$2(HttpLayer)); +const program = gen(function* () { + return (yield* Client).get("/models"); +}); +assert.deepStrictEqual(await runPromise(provide(program, ClientLayer)), "GET mock:/models"); +assert.deepStrictEqual(log, ["piped", "make mock:"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/client.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/client.js new file mode 100644 index 000000000000..5b1743d13f91 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/client.js @@ -0,0 +1,8 @@ +const unusedHelper = () => "unused" + +// Builds the client object: the provider's object literal is returned from here. +export const build = (http) => ({ + http, + get: (path) => http.request(path), + unused: () => unusedHelper() +}) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/main.js new file mode 100644 index 000000000000..25de5b351efb --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_function/main.js @@ -0,0 +1,38 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import { build } from "./client.js" + +// The shape of a generated client: a class-form key, provided by +// `Layer.effect(Key, make(options))`, where `make` is an `Effect.fnUntraced` +// generator returning the object built by a function in another module. The +// piped `Effect.updateService` only changes the constructor's context, and its +// callback runs before the constructor body. +class Client extends Context.Service()("test/RealProviderConstructorClient") {} +class Http extends Context.Service()("test/RealProviderConstructorHttp") {} + +const log = [] + +const make = Effect.fnUntraced( + function* (options) { + const http = yield* Http + log.push(`make ${options.base}`) + return build({ request: (path) => http.request(`${options.base}${path}`) }) + }, + Effect.updateService(Http, (http) => { + log.push("piped") + return http + }) +) + +const HttpLayer = Layer.succeed(Http, { request: (url) => `GET ${url}` }) +const ClientLayer = Layer.effect(Client, make({ base: "mock:" })).pipe(Layer.provide(HttpLayer)) + +const program = Effect.gen(function* () { + const client = yield* Client + return client.get("/models") +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, ClientLayer)), "GET mock:/models") +assert.deepStrictEqual(log, ["piped", "make mock:"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/_test.mjs new file mode 100644 index 000000000000..1c49008ee2ac --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} +for (const name of []) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/artifacts.snap new file mode 100644 index 000000000000..0b7b7cd64627 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/artifacts.snap @@ -0,0 +1,4821 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make$1(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make$1 = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make$1(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync$1(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync$1 = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced$1 = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const succeedPayload = function(_value, fiber) { + return fiber.succeedWith(this.payload); +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +const tapCont = function(value) { + const f = this.payload; + return new ContImpl(f(value), succeedPayload, value); +}; +const tapEffectCont = function(value) { + return new ContImpl(this.payload, succeedPayload, value); +}; +/** @internal */ +const tap$1 = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, isEffect(f) ? tapEffectCont : tapCont, f)); +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced$1(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync$1(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make$1(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Creates an `Effect` that represents a synchronous side-effectful computation. +* +* **When to use** +* +* Use when you need to wrap a synchronous side-effectful operation that is not +* expected to throw. +* +* **Details** +* +* The provided function is evaluated lazily when the effect runs. +* +* **Gotchas** +* +* The function must not throw. If it throws, the thrown value is treated as a +* defect, not as a typed failure. Use `try` when throwing is expected. +* +* **Example** (Capturing synchronous logging in an Effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* const log = (message: string) => +* Effect.sync(() => { +* void output.push(message) // side effect +* }) +* +* // ┌─── Effect +* // ▼ +* const program = log("Hello, World!") +* Effect.runSync(program) +* output // => ["Hello, World!"] +* ``` +* +* @see {@link try_ | try} for a version that can handle failures. +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const sync = sync$1; +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Runs a side effect with the result of an effect without changing the original +* value. +* +* **When to use** +* +* Use when you need to run an effectful observation, such as logging or +* tracking, while passing the original success value to the next step. +* +* **Details** +* +* `tap` works similarly to `flatMap`, but it ignores the result of the function +* passed to it. The value from the previous effect remains available for the +* next part of the chain. Note that if the side effect fails, the entire chain +* will fail too. +* +* **Example** (Logging a step in a pipeline) +* +* ```ts import.meta.vitest +* import { Data, Effect, pipe } from "effect" +* const output: Array = [] +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* // Function to apply a discount safely to a transaction amount +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* // Simulated asynchronous task to fetch a transaction amount from database +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const finalAmount = pipe( +* fetchTransactionAmount, +* // Log the fetched transaction amount +* Effect.tap((amount) => Effect.sync(() => { output.push(`Apply a discount to: ${amount}`) })), +* // `amount` is still available! +* Effect.flatMap((amount) => applyDiscount(amount, 5)) +* ) +* +* void output.push(await Effect.runPromise(finalAmount)) +* output // => ["Apply a discount to: 100", 95] +* ``` +* +* @stability stable +* @category sequencing +* @since 2.0.0 +*/ +const tap = tap$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +/** +* Creates an Effect-returning function without tracing. +* +* **When to use** +* +* Use when you are defining a reusable Effect function whose implementation +* would otherwise be a normal function returning {@link gen}, especially when +* tracing spans or stack-frame capture are not needed. +* +* **Details** +* +* Compared to a plain function that returns {@link gen}, `Effect.fnUntraced` +* reuses the generator body instead of allocating a fresh generator closure +* around the arguments on every call. It does not record an Effect stack-frame +* boundary and does not create tracing spans. Use {@link fn} when you need +* those stack frames or spans. Additional arguments after the generator body +* act like `pipe` transforms: each transform receives the previous result and +* the original function arguments. Generator bodies may declare a `this` +* parameter; pass `{ self }` before the body to bind `this` when the function +* is created. Annotate the generator return type with +* `Effect.fn.Return` when the produced `Effect` type needs to be +* stated explicitly. +* +* **Example** (Defining untraced effect functions) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ) { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Transforming the returned Effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced( +* function*(value: string) { +* return yield* Effect.succeed(value.length) +* }, +* (effect, value) => +* effect.pipe(Effect.map((length) => `${value}: ${length}`)) +* ) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello: 5" +* ``` +* +* **Example** (Annotating an untraced non-parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ): Effect.fn.Return { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Annotating an untraced parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: A +* ): Effect.fn.Return { +* return yield* Effect.succeed(value) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello" +* ``` +* +* @stability stable +* @category constructors +* @since 3.12.0 +*/ +const fnUntraced = fnUntraced$1; +// client.js +const unusedHelper = () => "unused"; +const build = () => ({ + get: () => "got", + unused: () => unusedHelper() +}); +// main.js +var Client = class extends Service()("test/RealProviderConstructorPipeableEscape") {}; +const observed = []; +const ClientLayer = effect(Client, fnUntraced(function* () { + return build(); +}, (effect) => tap(effect, (client) => sync(() => observed.push(client[["un", "used"].join("")]()))))()); +const program = gen(function* () { + return (yield* Client).get(); +}); +assert.deepStrictEqual(await runPromise(provide(program, ClientLayer)), "got"); +assert.deepStrictEqual(observed, ["unused"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/client.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/client.js new file mode 100644 index 000000000000..79c192cec546 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/client.js @@ -0,0 +1,7 @@ +const unusedHelper = () => "unused" + +// Builds the client object for the provider and for a direct caller. +export const build = () => ({ + get: () => "got", + unused: () => unusedHelper() +}) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/main.js new file mode 100644 index 000000000000..824a4c47c120 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_pipeable_escape/main.js @@ -0,0 +1,29 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import { build } from "./client.js" + +// An arbitrary pipeable of the constructor receives the Effect that builds the +// object and can hand the object to user code, here reading a method by a name +// known only at run time. The constructor is not followed, so it stays whole. +class Client extends Context.Service()("test/RealProviderConstructorPipeableEscape") {} + +const observed = [] + +const make = Effect.fnUntraced( + function* () { + return build() + }, + (effect) => Effect.tap(effect, (client) => Effect.sync(() => observed.push(client[["un", "used"].join("")]()))) +) + +const ClientLayer = Layer.effect(Client, make()) + +const program = Effect.gen(function* () { + const client = yield* Client + return client.get() +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, ClientLayer)), "got") +assert.deepStrictEqual(observed, ["unused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_recursive/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_recursive/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_recursive/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_recursive/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_recursive/artifacts.snap new file mode 100644 index 000000000000..f9e56d29f7ec --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_recursive/artifacts.snap @@ -0,0 +1,4712 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make$1(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make$1 = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make$1(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced$1 = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced$1(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make$1(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +/** +* Creates an Effect-returning function without tracing. +* +* **When to use** +* +* Use when you are defining a reusable Effect function whose implementation +* would otherwise be a normal function returning {@link gen}, especially when +* tracing spans or stack-frame capture are not needed. +* +* **Details** +* +* Compared to a plain function that returns {@link gen}, `Effect.fnUntraced` +* reuses the generator body instead of allocating a fresh generator closure +* around the arguments on every call. It does not record an Effect stack-frame +* boundary and does not create tracing spans. Use {@link fn} when you need +* those stack frames or spans. Additional arguments after the generator body +* act like `pipe` transforms: each transform receives the previous result and +* the original function arguments. Generator bodies may declare a `this` +* parameter; pass `{ self }` before the body to bind `this` when the function +* is created. Annotate the generator return type with +* `Effect.fn.Return` when the produced `Effect` type needs to be +* stated explicitly. +* +* **Example** (Defining untraced effect functions) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ) { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Transforming the returned Effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced( +* function*(value: string) { +* return yield* Effect.succeed(value.length) +* }, +* (effect, value) => +* effect.pipe(Effect.map((length) => `${value}: ${length}`)) +* ) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello: 5" +* ``` +* +* **Example** (Annotating an untraced non-parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ): Effect.fn.Return { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Annotating an untraced parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: A +* ): Effect.fn.Return { +* return yield* Effect.succeed(value) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello" +* ``` +* +* @stability stable +* @category constructors +* @since 3.12.0 +*/ +const fnUntraced = fnUntraced$1; +// main.js +const Store = Service("test/RealProviderConstructorRecursive"); +const make = fnUntraced(function* (n) { + if (n === 0) return { + readOne: () => "read", + unused: () => "unused" + }; + return yield* make(n - 1); +}); +const StoreLayer = effect(Store, make(1)); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +assert.strictEqual(await runPromise(provide(program, StoreLayer)), "read"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_recursive/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_recursive/main.js new file mode 100644 index 000000000000..90a646884fe3 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_recursive/main.js @@ -0,0 +1,21 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A constructor that returns its own result for a smaller argument. Following +// its returns must stop at the cycle; the program terminates at run time. +const Store = Context.Service("test/RealProviderConstructorRecursive") + +const make = Effect.fnUntraced(function* (n) { + if (n === 0) return { readOne: () => "read", unused: () => "unused" } + return yield* make(n - 1) +}) + +const StoreLayer = Layer.effect(Store, make(1)) + +const program = Effect.gen(function* () { + return (yield* Store).readOne() +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), "read") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/_test.mjs new file mode 100644 index 000000000000..1c49008ee2ac --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/_test.mjs @@ -0,0 +1,14 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} +for (const name of []) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/artifacts.snap new file mode 100644 index 000000000000..af3aaef75ce8 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/artifacts.snap @@ -0,0 +1,4716 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make$1(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make$1 = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make$1(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced$1 = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced$1(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make$1(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +/** +* Creates an Effect-returning function without tracing. +* +* **When to use** +* +* Use when you are defining a reusable Effect function whose implementation +* would otherwise be a normal function returning {@link gen}, especially when +* tracing spans or stack-frame capture are not needed. +* +* **Details** +* +* Compared to a plain function that returns {@link gen}, `Effect.fnUntraced` +* reuses the generator body instead of allocating a fresh generator closure +* around the arguments on every call. It does not record an Effect stack-frame +* boundary and does not create tracing spans. Use {@link fn} when you need +* those stack frames or spans. Additional arguments after the generator body +* act like `pipe` transforms: each transform receives the previous result and +* the original function arguments. Generator bodies may declare a `this` +* parameter; pass `{ self }` before the body to bind `this` when the function +* is created. Annotate the generator return type with +* `Effect.fn.Return` when the produced `Effect` type needs to be +* stated explicitly. +* +* **Example** (Defining untraced effect functions) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ) { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Transforming the returned Effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced( +* function*(value: string) { +* return yield* Effect.succeed(value.length) +* }, +* (effect, value) => +* effect.pipe(Effect.map((length) => `${value}: ${length}`)) +* ) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello: 5" +* ``` +* +* **Example** (Annotating an untraced non-parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ): Effect.fn.Return { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Annotating an untraced parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: A +* ): Effect.fn.Return { +* return yield* Effect.succeed(value) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello" +* ``` +* +* @stability stable +* @category constructors +* @since 3.12.0 +*/ +const fnUntraced = fnUntraced$1; +// client.js +const unusedHelper = () => "unused"; +const build = () => ({ + get: () => "got", + unused: () => unusedHelper() +}); +// main.js +var Client = class extends Service()("test/RealProviderConstructorShared") {}; +const ClientLayer = effect(Client, fnUntraced(function* () { + return build(); +})()); +const program = gen(function* () { + const client = yield* Client; + const direct = build(); + const name = ["un", "used"].join(""); + return [client.get(), direct[name]()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, ClientLayer)), ["got", "unused"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/client.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/client.js new file mode 100644 index 000000000000..79c192cec546 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/client.js @@ -0,0 +1,7 @@ +const unusedHelper = () => "unused" + +// Builds the client object for the provider and for a direct caller. +export const build = () => ({ + get: () => "got", + unused: () => unusedHelper() +}) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/main.js new file mode 100644 index 000000000000..618fa4917b4f --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_constructor_shared/main.js @@ -0,0 +1,25 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import { build } from "./client.js" + +// The function that builds the provider's object is also called directly, and +// that object's methods are read by a name known only at run time. Removing a +// property from the shared literal would break the direct caller, so it stays. +class Client extends Context.Service()("test/RealProviderConstructorShared") {} + +const make = Effect.fnUntraced(function* () { + return build() +}) + +const ClientLayer = Layer.effect(Client, make()) + +const program = Effect.gen(function* () { + const client = yield* Client + const direct = build() + const name = ["un", "used"].join("") + return [client.get(), direct[name]()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, ClientLayer)), ["got", "unused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/_test.mjs new file mode 100644 index 000000000000..23bacbb37528 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/_test.mjs @@ -0,0 +1,13 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Each binding is initialised where its provider is built: the unread +// properties are removed. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["parameterUnused", "bodyUnused", "varUnused"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/artifacts.snap new file mode 100644 index 000000000000..05fec1b6917e --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/artifacts.snap @@ -0,0 +1,4702 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results$1.get(self); + if (!known) results$1.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results$1 = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/record.js +/** @internal */ +function assignProperty(self, key, value) { + if (key === "__proto__") Object.defineProperty(self, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + else self[key] = value; +} +/** @internal */ +function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } + for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProperty(self, key, source[key]); +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +var Fail = class extends ReasonBase { + constructor(error, annotations = constEmptyAnnotations) { + super("Fail", annotations, error); + this.error = error; + } + toString() { + return `Fail(${format(this.error)})`; + } + toJSON() { + return { + _tag: "Fail", + error: this.error + }; + } + [symbol](that) { + return isFailReason(that) && equals(this.error, that.error) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.error))(hash(this.annotations))); + } +}; +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +const causeFail = (error) => new CauseImpl([new Fail(error)]); +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitFail = (e) => exitFailCause(causeFail(e)); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const YieldableError = /*#__PURE__*/ function() { + class YieldableError extends globalThis.Error {} + const proto = /*#__PURE__*/ makePrimitiveProto({ + op: "YieldableError", + [evaluate]() { + return exitFail(this); + } + }); + delete proto.toString; + Object.assign(YieldableError.prototype, proto); + return YieldableError; +}(); +/** @internal */ +const Error$1 = /*#__PURE__*/ function() { + const plainArgsSymbol = /*#__PURE__*/ Symbol.for("effect/Data/Error/plainArgs"); + return class Base extends YieldableError { + constructor(args) { + super(args?.message, args?.cause ? { cause: args.cause } : void 0); + if (args) { + assignProperties(this, args); + Object.defineProperty(this, plainArgsSymbol, { + value: args, + enumerable: false + }); + } + } + toJSON() { + return { + ...this[plainArgsSymbol], + ...this + }; + } + }; +}(); +/** @internal */ +const TaggedError = (tag) => { + class Base extends Error$1 { + _tag = tag; + } + Base.prototype.name = tag; + return Base; +}; +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runSyncExitWith = (context) => { + const runFork = runForkWith(context); + return (effect) => { + if (effectIsExit(effect)) return effect; + const scheduler = new MixedScheduler("sync"); + const fiber = runFork(effect, { scheduler }); + fiber._dispatcher?.flush(); + return fiber._exit ?? exitDie(new AsyncFiberError(fiber)); + }; +}; +/** @internal */ +const runSyncWith = (context) => { + const runSyncExit = runSyncExitWith(context); + return (effect) => { + const exit = runSyncExit(effect); + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }; +}; +/** @internal */ +const runSync$1 = /*#__PURE__*/ runSyncWith(/*#__PURE__*/ empty$1()); +/** @internal */ +const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError"; +/** @internal */ +var AsyncFiberError = class extends (/*#__PURE__*/ TaggedError("AsyncFiberError")) { + [AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId; + constructor(fiber) { + super({ + message: "An asynchronous Effect was executed with Effect.runSync", + fiber + }); + } +}; +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect synchronously and returns its success value. +* +* **When to use** +* +* Use when you need to execute an effect that is guaranteed to complete +* synchronously. +* +* **Details** +* +* If the effect fails, dies, or is interrupted, `runSync` throws the squashed +* cause instead of returning a value. Typed errors can be thrown directly, +* including non-Error values. Asynchronous work throws `Cause.AsyncFiberError`. +* Use `runSyncExit` when you want the failure captured as an `Exit`. +* +* **Example** (Running a synchronous effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* const program = Effect.sync(() => { +* void output.push("Hello, World!") +* return 1 +* }) +* +* const result = Effect.runSync(program) +* void output.push(result) +* output // => ["Hello, World!", 1] +* ``` +* +* **Example** (Throwing for failed or async effects) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* try { +* // Attempt to run an effect that fails +* Effect.runSync(Effect.fail("my error")) +* } catch (e) { +* void output.push("failed effect") +* } +* try { +* // Attempt to run an effect that involves async work +* Effect.runSync(Effect.promise(() => Promise.resolve(1))) +* } catch (e) { +* void output.push("async effect") +* } +* output // => ["failed effect", "async effect"] +* ``` +* +* @see {@link runSyncExit} for a version that returns an `Exit` type instead of +* throwing an error. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runSync = runSync$1; +// main.js +const ParameterBody = Service("test/RealInitializedParameterBody"); +const LoopBody = Service("test/RealInitializedLoopBody"); +const VarHead = Service("test/RealInitializedVarHead"); +const readParameterBody = gen(function* () { + return (yield* ParameterBody).readOne(); +}); +const readLoopBody = gen(function* () { + return (yield* LoopBody).readOne(); +}); +const readVarHead = gen(function* () { + return (yield* VarHead).readOne(); +}); +function provideParameter(parameterHelper) { + return runSync(provide(readParameterBody, succeed(ParameterBody, { readOne: () => "read" }))); +} +assert.strictEqual(provideParameter(() => "unused"), "read"); +const results = []; +for (const bodyHelper of [() => "unused"]) results.push(runSync(provide(readLoopBody, succeed(LoopBody, { readOne: () => "read" })))); +assert.deepStrictEqual(results, ["read"]); +const heads = []; +for (var varHelper of [runSync(provide(readVarHead, succeed(VarHead, { readOne: () => "read" })))]) heads.push(varHelper); +assert.deepStrictEqual(heads, ["read"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/main.js new file mode 100644 index 000000000000..76d236698c59 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_bindings_prune/main.js @@ -0,0 +1,51 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Controls for the temporal dead zone checks: each provider reads a binding +// that is initialised where the provider is built, so the unread property can +// go. A parameter read in the function body, a lexical loop-head binding read +// in the loop body, and a `var` loop-head binding (undefined, not throwing) +// read in the loop's right-hand side. +const ParameterBody = Context.Service("test/RealInitializedParameterBody") +const LoopBody = Context.Service("test/RealInitializedLoopBody") +const VarHead = Context.Service("test/RealInitializedVarHead") + +const readParameterBody = Effect.gen(function* () { + return (yield* ParameterBody).readOne() +}) +const readLoopBody = Effect.gen(function* () { + return (yield* LoopBody).readOne() +}) +const readVarHead = Effect.gen(function* () { + return (yield* VarHead).readOne() +}) + +function provideParameter(parameterHelper) { + return Effect.runSync( + Effect.provide( + readParameterBody, + Layer.succeed(ParameterBody, { readOne: () => "read", parameterUnused: parameterHelper }) + ) + ) +} +assert.strictEqual(provideParameter(() => "unused"), "read") + +const results = [] +for (const bodyHelper of [() => "unused"]) { + results.push( + Effect.runSync( + Effect.provide(readLoopBody, Layer.succeed(LoopBody, { readOne: () => "read", bodyUnused: bodyHelper })) + ) + ) +} +assert.deepStrictEqual(results, ["read"]) + +const heads = [] +for (var varHelper of [ + Effect.runSync(Effect.provide(readVarHead, Layer.succeed(VarHead, { readOne: () => "read", varUnused: varHelper }))) +]) { + heads.push(varHelper) +} +assert.deepStrictEqual(heads, ["read"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/_test.mjs new file mode 100644 index 000000000000..4eadccf0ef8b --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/_test.mjs @@ -0,0 +1,11 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The catch binding is initialised in the catch body: the unread property is +// removed. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +assert.doesNotMatch(code, /\bcatchUnused\b/, "catchUnused should be removed") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/artifacts.snap new file mode 100644 index 000000000000..d54fe9bae607 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/artifacts.snap @@ -0,0 +1,4691 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/record.js +/** @internal */ +function assignProperty(self, key, value) { + if (key === "__proto__") Object.defineProperty(self, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + else self[key] = value; +} +/** @internal */ +function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } + for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProperty(self, key, source[key]); +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +var Fail = class extends ReasonBase { + constructor(error, annotations = constEmptyAnnotations) { + super("Fail", annotations, error); + this.error = error; + } + toString() { + return `Fail(${format(this.error)})`; + } + toJSON() { + return { + _tag: "Fail", + error: this.error + }; + } + [symbol](that) { + return isFailReason(that) && equals(this.error, that.error) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.error))(hash(this.annotations))); + } +}; +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +const causeFail = (error) => new CauseImpl([new Fail(error)]); +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitFail = (e) => exitFailCause(causeFail(e)); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const YieldableError = /*#__PURE__*/ function() { + class YieldableError extends globalThis.Error {} + const proto = /*#__PURE__*/ makePrimitiveProto({ + op: "YieldableError", + [evaluate]() { + return exitFail(this); + } + }); + delete proto.toString; + Object.assign(YieldableError.prototype, proto); + return YieldableError; +}(); +/** @internal */ +const Error$1 = /*#__PURE__*/ function() { + const plainArgsSymbol = /*#__PURE__*/ Symbol.for("effect/Data/Error/plainArgs"); + return class Base extends YieldableError { + constructor(args) { + super(args?.message, args?.cause ? { cause: args.cause } : void 0); + if (args) { + assignProperties(this, args); + Object.defineProperty(this, plainArgsSymbol, { + value: args, + enumerable: false + }); + } + } + toJSON() { + return { + ...this[plainArgsSymbol], + ...this + }; + } + }; +}(); +/** @internal */ +const TaggedError = (tag) => { + class Base extends Error$1 { + _tag = tag; + } + Base.prototype.name = tag; + return Base; +}; +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runSyncExitWith = (context) => { + const runFork = runForkWith(context); + return (effect) => { + if (effectIsExit(effect)) return effect; + const scheduler = new MixedScheduler("sync"); + const fiber = runFork(effect, { scheduler }); + fiber._dispatcher?.flush(); + return fiber._exit ?? exitDie(new AsyncFiberError(fiber)); + }; +}; +/** @internal */ +const runSyncWith = (context) => { + const runSyncExit = runSyncExitWith(context); + return (effect) => { + const exit = runSyncExit(effect); + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }; +}; +/** @internal */ +const runSync$1 = /*#__PURE__*/ runSyncWith(/*#__PURE__*/ empty$1()); +/** @internal */ +const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError"; +/** @internal */ +var AsyncFiberError = class extends (/*#__PURE__*/ TaggedError("AsyncFiberError")) { + [AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId; + constructor(fiber) { + super({ + message: "An asynchronous Effect was executed with Effect.runSync", + fiber + }); + } +}; +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect synchronously and returns its success value. +* +* **When to use** +* +* Use when you need to execute an effect that is guaranteed to complete +* synchronously. +* +* **Details** +* +* If the effect fails, dies, or is interrupted, `runSync` throws the squashed +* cause instead of returning a value. Typed errors can be thrown directly, +* including non-Error values. Asynchronous work throws `Cause.AsyncFiberError`. +* Use `runSyncExit` when you want the failure captured as an `Exit`. +* +* **Example** (Running a synchronous effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* const program = Effect.sync(() => { +* void output.push("Hello, World!") +* return 1 +* }) +* +* const result = Effect.runSync(program) +* void output.push(result) +* output // => ["Hello, World!", 1] +* ``` +* +* **Example** (Throwing for failed or async effects) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* try { +* // Attempt to run an effect that fails +* Effect.runSync(Effect.fail("my error")) +* } catch (e) { +* void output.push("failed effect") +* } +* try { +* // Attempt to run an effect that involves async work +* Effect.runSync(Effect.promise(() => Promise.resolve(1))) +* } catch (e) { +* void output.push("async effect") +* } +* output // => ["failed effect", "async effect"] +* ``` +* +* @see {@link runSyncExit} for a version that returns an `Exit` type instead of +* throwing an error. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runSync = runSync$1; +// main.js +const CatchBody = Service("test/RealInitializedCatchBody"); +const readCatchBody = gen(function* () { + return (yield* CatchBody).readOne(); +}); +let result; +try { + throw { catchHelper: () => "unused" }; +} catch ({ catchHelper }) { + result = runSync(provide(readCatchBody, succeed(CatchBody, { readOne: () => "read" }))); +} +assert.strictEqual(result, "read"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/main.js new file mode 100644 index 000000000000..399775188a03 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_initialized_catch_body_prune/main.js @@ -0,0 +1,22 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Control for the catch-binding check: a destructured catch binding read in +// the catch body is initialised, so the unread property can go. +const CatchBody = Context.Service("test/RealInitializedCatchBody") + +const readCatchBody = Effect.gen(function* () { + return (yield* CatchBody).readOne() +}) + +let result +try { + throw { catchHelper: () => "unused" } +} catch ({ catchHelper }) { + result = Effect.runSync( + Effect.provide(readCatchBody, Layer.succeed(CatchBody, { readOne: () => "read", catchUnused: catchHelper })) + ) +} +assert.strictEqual(result, "read") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/_test.mjs new file mode 100644 index 000000000000..13a0d9f71137 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Every method of every service stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["syncUnused", "genUnused", "makeUnused"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/artifacts.snap new file mode 100644 index 000000000000..fe490586c538 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/artifacts.snap @@ -0,0 +1,4788 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make$1(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make$1 = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make$1(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync$1(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync$1 = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced$1 = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced$1(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync$1(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make$1(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Creates an `Effect` that represents a synchronous side-effectful computation. +* +* **When to use** +* +* Use when you need to wrap a synchronous side-effectful operation that is not +* expected to throw. +* +* **Details** +* +* The provided function is evaluated lazily when the effect runs. +* +* **Gotchas** +* +* The function must not throw. If it throws, the thrown value is treated as a +* defect, not as a typed failure. Use `try` when throwing is expected. +* +* **Example** (Capturing synchronous logging in an Effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* const log = (message: string) => +* Effect.sync(() => { +* void output.push(message) // side effect +* }) +* +* // ┌─── Effect +* // ▼ +* const program = log("Hello, World!") +* Effect.runSync(program) +* output // => ["Hello, World!"] +* ``` +* +* @see {@link try_ | try} for a version that can handle failures. +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const sync = sync$1; +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +/** +* Creates an Effect-returning function without tracing. +* +* **When to use** +* +* Use when you are defining a reusable Effect function whose implementation +* would otherwise be a normal function returning {@link gen}, especially when +* tracing spans or stack-frame capture are not needed. +* +* **Details** +* +* Compared to a plain function that returns {@link gen}, `Effect.fnUntraced` +* reuses the generator body instead of allocating a fresh generator closure +* around the arguments on every call. It does not record an Effect stack-frame +* boundary and does not create tracing spans. Use {@link fn} when you need +* those stack frames or spans. Additional arguments after the generator body +* act like `pipe` transforms: each transform receives the previous result and +* the original function arguments. Generator bodies may declare a `this` +* parameter; pass `{ self }` before the body to bind `this` when the function +* is created. Annotate the generator return type with +* `Effect.fn.Return` when the produced `Effect` type needs to be +* stated explicitly. +* +* **Example** (Defining untraced effect functions) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ) { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Transforming the returned Effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced( +* function*(value: string) { +* return yield* Effect.succeed(value.length) +* }, +* (effect, value) => +* effect.pipe(Effect.map((length) => `${value}: ${length}`)) +* ) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello: 5" +* ``` +* +* **Example** (Annotating an untraced non-parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: string +* ): Effect.fn.Return { +* return yield* Effect.succeed(value.length) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => 5 +* ``` +* +* **Example** (Annotating an untraced parametric function) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* const f = Effect.fnUntraced(function*( +* value: A +* ): Effect.fn.Return { +* return yield* Effect.succeed(value) +* }) +* +* // ┌─── Effect.Effect +* // ▼ +* const program = f("hello") +* Effect.runSync(program) // => "hello" +* ``` +* +* @stability stable +* @category constructors +* @since 3.12.0 +*/ +const fnUntraced = fnUntraced$1; +// main.js +const SyncStore = Service("test/RealNamedCallbackSync"); +const GenStore = Service("test/RealNamedCallbackGen"); +const MakeStore = Service("test/RealNamedCallbackMake"); +let exposedSync; +const SyncLayer = effect(SyncStore, sync(function syncInner() { + exposedSync = syncInner; + return { + readOne: () => "read", + syncUnused: () => "syncUnused" + }; +})); +let exposedGen; +const GenLayer = effect(GenStore, gen(function* genInner() { + exposedGen = genInner; + return { + readOne: () => "read", + genUnused: () => "genUnused" + }; +})); +function makeLayer() { + return effect(MakeStore, make()); +} +let exposedMake; +const make = fnUntraced(function* makeInner() { + exposedMake = makeInner; + const readOne = () => "read"; + const makeUnused = () => "makeUnused"; + return { + readOne, + makeUnused + }; +}); +const program = gen(function* () { + return [ + (yield* SyncStore).readOne(), + (yield* GenStore).readOne(), + (yield* MakeStore).readOne() + ]; +}); +const layer = mergeAll(SyncLayer, GenLayer, makeLayer()); +assert.deepStrictEqual(await runPromise(provide(program, layer)), [ + "read", + "read", + "read" +]); +assert.strictEqual(exposedSync().syncUnused(), "syncUnused"); +assert.strictEqual(exposedGen().next().value.genUnused(), "genUnused"); +assert.strictEqual(exposedMake().next().value.makeUnused(), "makeUnused"); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/main.js new file mode 100644 index 000000000000..1c01b51dadfb --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_named_callback_escape/main.js @@ -0,0 +1,53 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Named provider callbacks hand themselves out through their inner names, so +// another caller gets an object from the same literal. One service per path +// that follows returns: `Effect.sync`, `Effect.gen` and an `Effect.fnUntraced` +// constructor. The Layer factory is declared before the constructor so the +// constructor's literal is a known provider object when it is visited. +const SyncStore = Context.Service("test/RealNamedCallbackSync") +const GenStore = Context.Service("test/RealNamedCallbackGen") +const MakeStore = Context.Service("test/RealNamedCallbackMake") + +let exposedSync +const SyncLayer = Layer.effect( + SyncStore, + Effect.sync(function syncInner() { + exposedSync = syncInner + return { readOne: () => "read", syncUnused: () => "syncUnused" } + }) +) + +let exposedGen +const GenLayer = Layer.effect( + GenStore, + Effect.gen(function* genInner() { + exposedGen = genInner + return { readOne: () => "read", genUnused: () => "genUnused" } + }) +) + +function makeLayer() { + return Layer.effect(MakeStore, make()) +} + +let exposedMake +const make = Effect.fnUntraced(function* makeInner() { + exposedMake = makeInner + const readOne = () => "read" + const makeUnused = () => "makeUnused" + return { readOne, makeUnused } +}) + +const program = Effect.gen(function* () { + return [(yield* SyncStore).readOne(), (yield* GenStore).readOne(), (yield* MakeStore).readOne()] +}) + +const layer = Layer.mergeAll(SyncLayer, GenLayer, makeLayer()) +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, layer)), ["read", "read", "read"]) +assert.strictEqual(exposedSync().syncUnused(), "syncUnused") +assert.strictEqual(exposedGen().next().value.genUnused(), "genUnused") +assert.strictEqual(exposedMake().next().value.makeUnused(), "makeUnused") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_catch_pattern/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_catch_pattern/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_catch_pattern/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_catch_pattern/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_catch_pattern/artifacts.snap new file mode 100644 index 000000000000..623af89f4c9d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_catch_pattern/artifacts.snap @@ -0,0 +1,4713 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/record.js +/** @internal */ +function assignProperty(self, key, value) { + if (key === "__proto__") Object.defineProperty(self, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + else self[key] = value; +} +/** @internal */ +function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } + for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProperty(self, key, source[key]); +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +var Fail = class extends ReasonBase { + constructor(error, annotations = constEmptyAnnotations) { + super("Fail", annotations, error); + this.error = error; + } + toString() { + return `Fail(${format(this.error)})`; + } + toJSON() { + return { + _tag: "Fail", + error: this.error + }; + } + [symbol](that) { + return isFailReason(that) && equals(this.error, that.error) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.error))(hash(this.annotations))); + } +}; +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +const causeFail = (error) => new CauseImpl([new Fail(error)]); +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitFail = (e) => exitFailCause(causeFail(e)); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const YieldableError = /*#__PURE__*/ function() { + class YieldableError extends globalThis.Error {} + const proto = /*#__PURE__*/ makePrimitiveProto({ + op: "YieldableError", + [evaluate]() { + return exitFail(this); + } + }); + delete proto.toString; + Object.assign(YieldableError.prototype, proto); + return YieldableError; +}(); +/** @internal */ +const Error$1 = /*#__PURE__*/ function() { + const plainArgsSymbol = /*#__PURE__*/ Symbol.for("effect/Data/Error/plainArgs"); + return class Base extends YieldableError { + constructor(args) { + super(args?.message, args?.cause ? { cause: args.cause } : void 0); + if (args) { + assignProperties(this, args); + Object.defineProperty(this, plainArgsSymbol, { + value: args, + enumerable: false + }); + } + } + toJSON() { + return { + ...this[plainArgsSymbol], + ...this + }; + } + }; +}(); +/** @internal */ +const TaggedError = (tag) => { + class Base extends Error$1 { + _tag = tag; + } + Base.prototype.name = tag; + return Base; +}; +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runSyncExitWith = (context) => { + const runFork = runForkWith(context); + return (effect) => { + if (effectIsExit(effect)) return effect; + const scheduler = new MixedScheduler("sync"); + const fiber = runFork(effect, { scheduler }); + fiber._dispatcher?.flush(); + return fiber._exit ?? exitDie(new AsyncFiberError(fiber)); + }; +}; +/** @internal */ +const runSyncWith = (context) => { + const runSyncExit = runSyncExitWith(context); + return (effect) => { + const exit = runSyncExit(effect); + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }; +}; +/** @internal */ +const runSync$1 = /*#__PURE__*/ runSyncWith(/*#__PURE__*/ empty$1()); +/** @internal */ +const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError"; +/** @internal */ +var AsyncFiberError = class extends (/*#__PURE__*/ TaggedError("AsyncFiberError")) { + [AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId; + constructor(fiber) { + super({ + message: "An asynchronous Effect was executed with Effect.runSync", + fiber + }); + } +}; +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect synchronously and returns its success value. +* +* **When to use** +* +* Use when you need to execute an effect that is guaranteed to complete +* synchronously. +* +* **Details** +* +* If the effect fails, dies, or is interrupted, `runSync` throws the squashed +* cause instead of returning a value. Typed errors can be thrown directly, +* including non-Error values. Asynchronous work throws `Cause.AsyncFiberError`. +* Use `runSyncExit` when you want the failure captured as an `Exit`. +* +* **Example** (Running a synchronous effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* const program = Effect.sync(() => { +* void output.push("Hello, World!") +* return 1 +* }) +* +* const result = Effect.runSync(program) +* void output.push(result) +* output // => ["Hello, World!", 1] +* ``` +* +* **Example** (Throwing for failed or async effects) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* try { +* // Attempt to run an effect that fails +* Effect.runSync(Effect.fail("my error")) +* } catch (e) { +* void output.push("failed effect") +* } +* try { +* // Attempt to run an effect that involves async work +* Effect.runSync(Effect.promise(() => Promise.resolve(1))) +* } catch (e) { +* void output.push("async effect") +* } +* output // => ["failed effect", "async effect"] +* ``` +* +* @see {@link runSyncExit} for a version that returns an `Exit` type instead of +* throwing an error. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runSync = runSync$1; +// main.js +const ObjectPattern = Service("test/RealTdzCatchObjectPattern"); +const ArrayPattern = Service("test/RealTdzCatchArrayPattern"); +const readObjectPattern = gen(function* () { + return (yield* ObjectPattern).readOne(); +}); +const readArrayPattern = gen(function* () { + return (yield* ArrayPattern).readOne(); +}); +const throwsReferenceError = (run) => { + try { + run(); + } catch (error) { + if (!(error instanceof ReferenceError)) throw error; + return true; + } + return false; +}; +assert.strictEqual(throwsReferenceError(() => { + try { + throw {}; + } catch ({ objectHelper = runSync(provide(readObjectPattern, succeed(ObjectPattern, { + readOne: () => "read", + unused: objectHelper + }))) }) {} +}), true); +assert.strictEqual(throwsReferenceError(() => { + try { + throw []; + } catch ([arrayHelper = runSync(provide(readArrayPattern, succeed(ArrayPattern, { + readOne: () => "read", + unused: arrayHelper + })))]) {} +}), true); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_catch_pattern/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_catch_pattern/main.js new file mode 100644 index 000000000000..93087e614fb0 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_catch_pattern/main.js @@ -0,0 +1,59 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A provider property reads a destructured catch binding inside that +// binding's own default, in an object and an array pattern. The binding is +// still in its temporal dead zone, so building the provider throws. Removing +// the unread property would drop that exception. +const ObjectPattern = Context.Service("test/RealTdzCatchObjectPattern") +const ArrayPattern = Context.Service("test/RealTdzCatchArrayPattern") + +const readObjectPattern = Effect.gen(function* () { + return (yield* ObjectPattern).readOne() +}) +const readArrayPattern = Effect.gen(function* () { + return (yield* ArrayPattern).readOne() +}) + +const throwsReferenceError = (run) => { + try { + run() + } catch (error) { + if (!(error instanceof ReferenceError)) throw error + return true + } + return false +} + +assert.strictEqual( + throwsReferenceError(() => { + try { + throw {} + } catch ({ + objectHelper = Effect.runSync( + Effect.provide( + readObjectPattern, + Layer.succeed(ObjectPattern, { readOne: () => "read", unused: objectHelper }) + ) + ) + }) { + } + }), + true +) + +assert.strictEqual( + throwsReferenceError(() => { + try { + throw [] + } catch ([ + arrayHelper = Effect.runSync( + Effect.provide(readArrayPattern, Layer.succeed(ArrayPattern, { readOne: () => "read", unused: arrayHelper })) + ) + ]) { + } + }), + true +) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/_test.mjs new file mode 100644 index 000000000000..bebd4b159bb5 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/_test.mjs @@ -0,0 +1,10 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The property that reads the uninitialised import stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +assert.match(code, /\bunused:/, "property unused should be kept") diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/artifacts.snap new file mode 100644 index 000000000000..031af575e428 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/artifacts.snap @@ -0,0 +1,4574 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// provider.js +const Store = Service("test/RealProviderTdzImportCycle"); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +let caught = false; +try { + await runPromise(provide(program, succeed(Store, { + readOne: () => "read", + unused: helper + }))); +} catch (error) { + caught = error instanceof ReferenceError; +} +const helper = () => "unused"; +// main.js +assert.strictEqual(caught, true); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/barrel.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/barrel.js new file mode 100644 index 000000000000..4ef0883cc227 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/barrel.js @@ -0,0 +1 @@ +export { helper as alias } from "./provider.js" diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/main.js new file mode 100644 index 000000000000..5a57d779f378 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/main.js @@ -0,0 +1,4 @@ +import assert from "node:assert" +import { caught } from "./provider.js" + +assert.strictEqual(caught, true) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/provider.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/provider.js new file mode 100644 index 000000000000..46a82bfd2db2 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_import_cycle/provider.js @@ -0,0 +1,26 @@ +import { alias } from "./barrel.js" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// `alias` resolves through the barrel back to `helper` in this module, which is +// still in its temporal dead zone when the provider is built, so building it +// throws. Removing the unread property would drop that exception. +const Store = Context.Service("test/RealProviderTdzImportCycle") + +const program = Effect.gen(function* () { + return (yield* Store).readOne() +}) + +export let caught = false +try { + const layer = Layer.succeed(Store, { + readOne: () => "read", + unused: alias + }) + await Effect.runPromise(Effect.provide(program, layer)) +} catch (error) { + caught = error instanceof ReferenceError +} + +export const helper = () => "unused" diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_own_initializer/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_own_initializer/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_own_initializer/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_own_initializer/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_own_initializer/artifacts.snap new file mode 100644 index 000000000000..5d5dc0996463 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_own_initializer/artifacts.snap @@ -0,0 +1,4714 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/record.js +/** @internal */ +function assignProperty(self, key, value) { + if (key === "__proto__") Object.defineProperty(self, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + else self[key] = value; +} +/** @internal */ +function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } + for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProperty(self, key, source[key]); +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +var Fail = class extends ReasonBase { + constructor(error, annotations = constEmptyAnnotations) { + super("Fail", annotations, error); + this.error = error; + } + toString() { + return `Fail(${format(this.error)})`; + } + toJSON() { + return { + _tag: "Fail", + error: this.error + }; + } + [symbol](that) { + return isFailReason(that) && equals(this.error, that.error) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.error))(hash(this.annotations))); + } +}; +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +const causeFail = (error) => new CauseImpl([new Fail(error)]); +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitFail = (e) => exitFailCause(causeFail(e)); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const YieldableError = /*#__PURE__*/ function() { + class YieldableError extends globalThis.Error {} + const proto = /*#__PURE__*/ makePrimitiveProto({ + op: "YieldableError", + [evaluate]() { + return exitFail(this); + } + }); + delete proto.toString; + Object.assign(YieldableError.prototype, proto); + return YieldableError; +}(); +/** @internal */ +const Error$1 = /*#__PURE__*/ function() { + const plainArgsSymbol = /*#__PURE__*/ Symbol.for("effect/Data/Error/plainArgs"); + return class Base extends YieldableError { + constructor(args) { + super(args?.message, args?.cause ? { cause: args.cause } : void 0); + if (args) { + assignProperties(this, args); + Object.defineProperty(this, plainArgsSymbol, { + value: args, + enumerable: false + }); + } + } + toJSON() { + return { + ...this[plainArgsSymbol], + ...this + }; + } + }; +}(); +/** @internal */ +const TaggedError = (tag) => { + class Base extends Error$1 { + _tag = tag; + } + Base.prototype.name = tag; + return Base; +}; +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runSyncExitWith = (context) => { + const runFork = runForkWith(context); + return (effect) => { + if (effectIsExit(effect)) return effect; + const scheduler = new MixedScheduler("sync"); + const fiber = runFork(effect, { scheduler }); + fiber._dispatcher?.flush(); + return fiber._exit ?? exitDie(new AsyncFiberError(fiber)); + }; +}; +/** @internal */ +const runSyncWith = (context) => { + const runSyncExit = runSyncExitWith(context); + return (effect) => { + const exit = runSyncExit(effect); + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }; +}; +/** @internal */ +const runSync$1 = /*#__PURE__*/ runSyncWith(/*#__PURE__*/ empty$1()); +/** @internal */ +const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError"; +/** @internal */ +var AsyncFiberError = class extends (/*#__PURE__*/ TaggedError("AsyncFiberError")) { + [AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId; + constructor(fiber) { + super({ + message: "An asynchronous Effect was executed with Effect.runSync", + fiber + }); + } +}; +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect synchronously and returns its success value. +* +* **When to use** +* +* Use when you need to execute an effect that is guaranteed to complete +* synchronously. +* +* **Details** +* +* If the effect fails, dies, or is interrupted, `runSync` throws the squashed +* cause instead of returning a value. Typed errors can be thrown directly, +* including non-Error values. Asynchronous work throws `Cause.AsyncFiberError`. +* Use `runSyncExit` when you want the failure captured as an `Exit`. +* +* **Example** (Running a synchronous effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* const program = Effect.sync(() => { +* void output.push("Hello, World!") +* return 1 +* }) +* +* const result = Effect.runSync(program) +* void output.push(result) +* output // => ["Hello, World!", 1] +* ``` +* +* **Example** (Throwing for failed or async effects) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* try { +* // Attempt to run an effect that fails +* Effect.runSync(Effect.fail("my error")) +* } catch (e) { +* void output.push("failed effect") +* } +* try { +* // Attempt to run an effect that involves async work +* Effect.runSync(Effect.promise(() => Promise.resolve(1))) +* } catch (e) { +* void output.push("async effect") +* } +* output // => ["failed effect", "async effect"] +* ``` +* +* @see {@link runSyncExit} for a version that returns an `Exit` type instead of +* throwing an error. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runSync = runSync$1; +// main.js +const Direct = Service("test/RealProviderTdzOwnInitializerDirect"); +const Nested = Service("test/RealProviderTdzOwnInitializerNested"); +const readDirect = gen(function* () { + return (yield* Direct).readOne(); +}); +let directCaught = false; +try { + const directHelper = runSync(provide(readDirect, succeed(Direct, { + readOne: () => "read", + unused: directHelper + }))); +} catch (error) { + if (!(error instanceof ReferenceError)) throw error; + directCaught = true; +} +assert.strictEqual(directCaught, true); +let nestedCaught = false; +try { + const nestedHelper = (() => { + const layer = succeed(Nested, { + readOne: () => "read", + unused: nestedHelper + }); + const readNested = gen(function* () { + return (yield* Nested).readOne(); + }); + runSync(provide(readNested, layer)); + return () => "unused"; + })(); +} catch (error) { + if (!(error instanceof ReferenceError)) throw error; + nestedCaught = true; +} +assert.strictEqual(nestedCaught, true); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_own_initializer/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_own_initializer/main.js new file mode 100644 index 000000000000..671f4979726a --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_own_initializer/main.js @@ -0,0 +1,42 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A provider property reads a binding inside that binding's own initializer, +// directly and from an immediately invoked function. The binding is still in +// its temporal dead zone, so building the provider throws. Removing the unread +// property would drop that exception. +const Direct = Context.Service("test/RealProviderTdzOwnInitializerDirect") +const Nested = Context.Service("test/RealProviderTdzOwnInitializerNested") + +const readDirect = Effect.gen(function* () { + return (yield* Direct).readOne() +}) + +let directCaught = false +try { + const directHelper = Effect.runSync( + Effect.provide(readDirect, Layer.succeed(Direct, { readOne: () => "read", unused: directHelper })) + ) +} catch (error) { + if (!(error instanceof ReferenceError)) throw error + directCaught = true +} +assert.strictEqual(directCaught, true) + +let nestedCaught = false +try { + const nestedHelper = (() => { + const layer = Layer.succeed(Nested, { readOne: () => "read", unused: nestedHelper }) + const readNested = Effect.gen(function* () { + return (yield* Nested).readOne() + }) + Effect.runSync(Effect.provide(readNested, layer)) + return () => "unused" + })() +} catch (error) { + if (!(error instanceof ReferenceError)) throw error + nestedCaught = true +} +assert.strictEqual(nestedCaught, true) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_parameters_and_loop_heads/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_parameters_and_loop_heads/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_parameters_and_loop_heads/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_parameters_and_loop_heads/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_parameters_and_loop_heads/artifacts.snap new file mode 100644 index 000000000000..3389c40e5af0 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_parameters_and_loop_heads/artifacts.snap @@ -0,0 +1,4731 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/record.js +/** @internal */ +function assignProperty(self, key, value) { + if (key === "__proto__") Object.defineProperty(self, key, { + value, + writable: true, + enumerable: true, + configurable: true + }); + else self[key] = value; +} +/** @internal */ +function assignProperties(self, source) { + if (!Object.hasOwn(source, "__proto__")) { + Object.assign(self, source); + return; + } + for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProperty(self, key, source[key]); +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +var Fail = class extends ReasonBase { + constructor(error, annotations = constEmptyAnnotations) { + super("Fail", annotations, error); + this.error = error; + } + toString() { + return `Fail(${format(this.error)})`; + } + toJSON() { + return { + _tag: "Fail", + error: this.error + }; + } + [symbol](that) { + return isFailReason(that) && equals(this.error, that.error) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.error))(hash(this.annotations))); + } +}; +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +const causeFail = (error) => new CauseImpl([new Fail(error)]); +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitFail = (e) => exitFailCause(causeFail(e)); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const YieldableError = /*#__PURE__*/ function() { + class YieldableError extends globalThis.Error {} + const proto = /*#__PURE__*/ makePrimitiveProto({ + op: "YieldableError", + [evaluate]() { + return exitFail(this); + } + }); + delete proto.toString; + Object.assign(YieldableError.prototype, proto); + return YieldableError; +}(); +/** @internal */ +const Error$1 = /*#__PURE__*/ function() { + const plainArgsSymbol = /*#__PURE__*/ Symbol.for("effect/Data/Error/plainArgs"); + return class Base extends YieldableError { + constructor(args) { + super(args?.message, args?.cause ? { cause: args.cause } : void 0); + if (args) { + assignProperties(this, args); + Object.defineProperty(this, plainArgsSymbol, { + value: args, + enumerable: false + }); + } + } + toJSON() { + return { + ...this[plainArgsSymbol], + ...this + }; + } + }; +}(); +/** @internal */ +const TaggedError = (tag) => { + class Base extends Error$1 { + _tag = tag; + } + Base.prototype.name = tag; + return Base; +}; +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runSyncExitWith = (context) => { + const runFork = runForkWith(context); + return (effect) => { + if (effectIsExit(effect)) return effect; + const scheduler = new MixedScheduler("sync"); + const fiber = runFork(effect, { scheduler }); + fiber._dispatcher?.flush(); + return fiber._exit ?? exitDie(new AsyncFiberError(fiber)); + }; +}; +/** @internal */ +const runSyncWith = (context) => { + const runSyncExit = runSyncExitWith(context); + return (effect) => { + const exit = runSyncExit(effect); + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }; +}; +/** @internal */ +const runSync$1 = /*#__PURE__*/ runSyncWith(/*#__PURE__*/ empty$1()); +/** @internal */ +const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError"; +/** @internal */ +var AsyncFiberError = class extends (/*#__PURE__*/ TaggedError("AsyncFiberError")) { + [AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId; + constructor(fiber) { + super({ + message: "An asynchronous Effect was executed with Effect.runSync", + fiber + }); + } +}; +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect synchronously and returns its success value. +* +* **When to use** +* +* Use when you need to execute an effect that is guaranteed to complete +* synchronously. +* +* **Details** +* +* If the effect fails, dies, or is interrupted, `runSync` throws the squashed +* cause instead of returning a value. Typed errors can be thrown directly, +* including non-Error values. Asynchronous work throws `Cause.AsyncFiberError`. +* Use `runSyncExit` when you want the failure captured as an `Exit`. +* +* **Example** (Running a synchronous effect) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* const program = Effect.sync(() => { +* void output.push("Hello, World!") +* return 1 +* }) +* +* const result = Effect.runSync(program) +* void output.push(result) +* output // => ["Hello, World!", 1] +* ``` +* +* **Example** (Throwing for failed or async effects) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* const output: Array = [] +* +* try { +* // Attempt to run an effect that fails +* Effect.runSync(Effect.fail("my error")) +* } catch (e) { +* void output.push("failed effect") +* } +* try { +* // Attempt to run an effect that involves async work +* Effect.runSync(Effect.promise(() => Promise.resolve(1))) +* } catch (e) { +* void output.push("async effect") +* } +* output // => ["failed effect", "async effect"] +* ``` +* +* @see {@link runSyncExit} for a version that returns an `Exit` type instead of +* throwing an error. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runSync = runSync$1; +// main.js +const SelfDefault = Service("test/RealTdzParameterSelfDefault"); +const LaterParameter = Service("test/RealTdzParameterLater"); +const ForOfHead = Service("test/RealTdzForOfHead"); +const ForInHead = Service("test/RealTdzForInHead"); +const readSelfDefault = gen(function* () { + return (yield* SelfDefault).readOne(); +}); +const readLaterParameter = gen(function* () { + return (yield* LaterParameter).readOne(); +}); +const readForOfHead = gen(function* () { + return (yield* ForOfHead).readOne(); +}); +const readForInHead = gen(function* () { + return (yield* ForInHead).readOne(); +}); +const throwsReferenceError = (run) => { + try { + run(); + } catch (error) { + if (!(error instanceof ReferenceError)) throw error; + return true; + } + return false; +}; +assert.strictEqual(throwsReferenceError(() => { + function build(selfHelper = runSync(provide(readSelfDefault, succeed(SelfDefault, { + readOne: () => "read", + unused: selfHelper + })))) {} + build(); +}), true); +assert.strictEqual(throwsReferenceError(() => { + const build = (first = runSync(provide(readLaterParameter, succeed(LaterParameter, { + readOne: () => "read", + unused: laterHelper + }))), laterHelper = () => "unused") => first; + build(); +}), true); +assert.strictEqual(throwsReferenceError(() => { + for (const ofHelper of [runSync(provide(readForOfHead, succeed(ForOfHead, { + readOne: () => "read", + unused: ofHelper + })))]); +}), true); +assert.strictEqual(throwsReferenceError(() => { + for (let inHelper in { key: runSync(provide(readForInHead, succeed(ForInHead, { + readOne: () => "read", + unused: inHelper + }))) }); +}), true); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_parameters_and_loop_heads/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_parameters_and_loop_heads/main.js new file mode 100644 index 000000000000..925657ca0490 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_parameters_and_loop_heads/main.js @@ -0,0 +1,85 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A provider property reads a binding that is still in its temporal dead zone: +// a parameter inside its own default, a later parameter from an earlier +// default, and a lexical loop-head binding while the loop's right-hand side +// runs. Building each provider throws. Removing the unread property would +// drop that exception. +const SelfDefault = Context.Service("test/RealTdzParameterSelfDefault") +const LaterParameter = Context.Service("test/RealTdzParameterLater") +const ForOfHead = Context.Service("test/RealTdzForOfHead") +const ForInHead = Context.Service("test/RealTdzForInHead") + +const readSelfDefault = Effect.gen(function* () { + return (yield* SelfDefault).readOne() +}) +const readLaterParameter = Effect.gen(function* () { + return (yield* LaterParameter).readOne() +}) +const readForOfHead = Effect.gen(function* () { + return (yield* ForOfHead).readOne() +}) +const readForInHead = Effect.gen(function* () { + return (yield* ForInHead).readOne() +}) + +const throwsReferenceError = (run) => { + try { + run() + } catch (error) { + if (!(error instanceof ReferenceError)) throw error + return true + } + return false +} + +assert.strictEqual( + throwsReferenceError(() => { + function build( + selfHelper = Effect.runSync( + Effect.provide(readSelfDefault, Layer.succeed(SelfDefault, { readOne: () => "read", unused: selfHelper })) + ) + ) {} + build() + }), + true +) + +assert.strictEqual( + throwsReferenceError(() => { + const build = ( + first = Effect.runSync( + Effect.provide( + readLaterParameter, + Layer.succeed(LaterParameter, { readOne: () => "read", unused: laterHelper }) + ) + ), + laterHelper = () => "unused" + ) => first + build() + }), + true +) + +assert.strictEqual( + throwsReferenceError(() => { + for (const ofHelper of [ + Effect.runSync(Effect.provide(readForOfHead, Layer.succeed(ForOfHead, { readOne: () => "read", unused: ofHelper }))) + ]) { + } + }), + true +) + +assert.strictEqual( + throwsReferenceError(() => { + for (let inHelper in { + key: Effect.runSync(Effect.provide(readForInHead, Layer.succeed(ForInHead, { readOne: () => "read", unused: inHelper }))) + }) { + } + }), + true +) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_reference/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_reference/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_reference/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_reference/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_reference/artifacts.snap new file mode 100644 index 000000000000..3abf48859d94 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_reference/artifacts.snap @@ -0,0 +1,4574 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealProviderTdz"); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +let caught = false; +try { + const layer = succeed(Store, { + readOne: () => "read", + unused: helper + }); + const helper = () => "unused"; + await runPromise(provide(program, layer)); +} catch (error) { + caught = error instanceof ReferenceError; +} +assert.strictEqual(caught, true); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_reference/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_reference/main.js new file mode 100644 index 000000000000..5f6c7fcd0943 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_reference/main.js @@ -0,0 +1,25 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// A provider property reads a binding still in its temporal dead zone, so building +// the provider throws. Removing the unread property would drop that exception. +const Store = Context.Service("test/RealProviderTdz") + +const program = Effect.gen(function* () { + return (yield* Store).readOne() +}) + +let caught = false +try { + const layer = Layer.succeed(Store, { + readOne: () => "read", + unused: helper + }) + const helper = () => "unused" + await Effect.runPromise(Effect.provide(program, layer)) +} catch (error) { + caught = error instanceof ReferenceError +} +assert.strictEqual(caught, true) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_switch/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_switch/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_switch/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_switch/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_switch/artifacts.snap new file mode 100644 index 000000000000..e694ab8c3e7a --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_switch/artifacts.snap @@ -0,0 +1,4577 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed$1(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed$1 = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed$1(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed$1(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed$1(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed$1([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed$1(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer that provides a single service from an already available +* value. +* +* **When to use** +* +* Use when you need a `Layer` that provides a service from an already +* constructed implementation without effectful acquisition. +* +* **Example** (Creating a layer from a service implementation) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const DatabaseLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) +* }) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, DatabaseLayer)) // => "Query result: SELECT 1" +* ``` +* +* @see {@link sync} for constructing layers from lazy values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeed = function() { + if (arguments.length === 1) return (resource) => succeedContext(make(arguments[0], resource)); + return succeedContext(make(arguments[0], arguments[1])); +}; +/** +* Constructs a layer that provides all services in an already available +* `Context`. +* +* **When to use** +* +* Use when you need a `Layer` built from an existing `Context`, including when +* you need to provide multiple services at once. +* +* **Details** +* +* This is a more general version of `succeed` that allows you to provide +* multiple services at once through a `Context`. +* +* **Example** (Providing multiple services from a context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* const context = Context.make(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }).pipe( +* Context.add(Logger, { +* log: (msg: string) => Effect.sync(() => logs.push(msg)) +* }) +* ) +* +* const layer = Layer.succeedContext(context) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, layer)) +* logs // => ["ready"] +* ``` +* +* @see {@link succeed} for providing a single service from a value +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const succeedContext = (context) => fromBuildUnsafe(constant(succeed$1(context))); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealProviderTdzSwitch"); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +let caught = false; +try { + switch (1) { + case 0: + const helper = () => "unused"; + break; + case 1: await runPromise(provide(program, succeed(Store, { + readOne: () => "read", + unused: helper + }))); + } +} catch (error) { + caught = error instanceof ReferenceError; +} +assert.strictEqual(caught, true); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_switch/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_switch/main.js new file mode 100644 index 000000000000..db478289d885 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/provider_tdz_switch/main.js @@ -0,0 +1,32 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// The cases of a switch share one scope. `helper` is declared earlier in the +// source, but entering `case 1` skips its initializer, so building the provider +// throws. Removing the unread property would drop that exception. +const Store = Context.Service("test/RealProviderTdzSwitch") + +const program = Effect.gen(function* () { + return (yield* Store).readOne() +}) + +let caught = false +try { + switch (Number("1")) { + case 0: + const helper = () => "unused" + break + case 1: + const layer = Layer.succeed(Store, { + readOne: () => "read", + unused: helper + }) + await Effect.runPromise(Effect.provide(program, layer)) + break + } +} catch (error) { + caught = error instanceof ReferenceError +} +assert.strictEqual(caught, true) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/_test.mjs new file mode 100644 index 000000000000..a698a820f53d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/_test.mjs @@ -0,0 +1,15 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["readHelper", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/artifacts.snap new file mode 100644 index 000000000000..a5c09a4d0051 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/artifacts.snap @@ -0,0 +1,4633 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealCleanData"); +const readHelper = () => "read"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + return Store.of({ readOne }); +})); +const settings = { + mode: "fast", + level: 2 +}; +const describe = () => { + const names = Object.keys(settings); + const values = []; + for (const name in settings) values.push(settings[name]); + const copy = structuredClone(settings); + return [ + names.join(","), + values.join(","), + Reflect.ownKeys(copy).length, + JSON.stringify(copy) + ]; +}; +const program = gen(function* () { + return [(yield* Store).readOne(), ...describe()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), [ + "read", + "mode,level", + "fast,2", + 2, + "{\"mode\":\"fast\",\"level\":2}" +]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/main.js new file mode 100644 index 000000000000..ca24f40b1e2a --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/reflection_clean_data/main.js @@ -0,0 +1,40 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// Positive gate: user code enumerates, indexes by non-constant names and serializes +// its own data, never an Effect runtime object. The pass must still remove `writeOne`. +const Store = Context.Service("test/RealCleanData") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +const settings = { mode: "fast", level: 2 } +const describe = () => { + const names = Object.keys(settings) + const values = [] + for (const name in settings) values.push(settings[name]) + const copy = structuredClone(settings) + return [names.join(","), values.join(","), Reflect.ownKeys(copy).length, JSON.stringify(copy)] +} +const program = Effect.gen(function* () { + return [(yield* Store).readOne(), ...describe()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), [ + "read", + "mode,level", + "fast,2", + 2, + '{"mode":"fast","level":2}' +]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/_test.mjs new file mode 100644 index 000000000000..a698a820f53d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/_test.mjs @@ -0,0 +1,15 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["readHelper", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/artifacts.snap new file mode 100644 index 000000000000..d828f4053b08 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/artifacts.snap @@ -0,0 +1,4719 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +const fiberInterruptChildren = (fiber) => { + if (fiber._children === void 0 || fiber._children.size === 0) return; + return fiberInterruptAll(fiber._children); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberJoin = (self) => { + const impl = self; + if (impl._exit) return impl._exit; + return callback((resume) => { + if (impl._exit) return resume(impl._exit); + return sync(self.addObserver(resume)); + }); +}; +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkChild$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, options) => withFiber((fiber) => { + interruptChildrenPatch(); + return succeed(forkUnsafe$1(fiber, self, options?.startImmediately, false, options?.uninterruptible ?? false)); +})); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +/** @internal */ +function interruptChildrenPatch() { + fiberMiddleware.interruptChildren ??= fiberInterruptChildren; +} +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Returns an effect that forks this effect into its own separate fiber, +* returning the fiber immediately, without waiting for it to begin executing +* the effect. +* +* **Details** +* +* You can use the `forkChild` method whenever you want to execute an effect in a +* new fiber, concurrently and without "blocking" the fiber executing other +* effects. Using fibers can be tricky, so instead of using this method +* directly, consider higher-level methods such as `Effect.race`, +* `Effect.raceFirst`, or `Effect.all` with a concurrency option. +* +* The fiber returned by this method has methods to interrupt the fiber and to +* wait for it to finish executing the effect. See `Fiber` for more +* information. +* +* Whenever you use this method to launch a new fiber, the new fiber is +* attached to the parent fiber's scope. This means when the parent fiber +* terminates, the child fiber will be terminated as well, ensuring that no +* fibers leak. This behavior is called "auto supervision", and if this +* behavior is not desired, you may use the `forkDetach` or `forkIn` methods. +* +* **Example** (Forking a child fiber) +* +* ```ts import.meta.vitest +* import { Effect, Fiber } from "effect" +* +* const task = Effect.succeed("result") +* +* const program = Effect.gen(function*() { +* const fiber = yield* task.pipe(Effect.forkChild) +* const result = yield* Fiber.join(fiber) +* return result +* }) +* +* await Effect.runPromise(program) // => "result" +* ``` +* +* @stability stable +* @category forking +* @since 4.0.0 +*/ +const forkChild = forkChild$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Fiber.js +/** +* Joins a fiber, blocking until it completes. If the fiber succeeds, +* returns its value. If it fails, the error is propagated. +* +* **When to use** +* +* Use when you need a forked fiber's failure to fail the current Effect because +* that fiber is part of the current workflow. +* +* **Gotchas** +* +* Joining a failed fiber propagates the fiber's Cause. Use {@link await_ await} when +* you need to inspect the `Exit` instead of failing. +* +* **Example** (Joining a fiber) +* +* ```ts import.meta.vitest +* import { Effect, Fiber } from "effect" +* +* const program = Effect.gen(function*() { +* const fiber = yield* Effect.forkChild(Effect.succeed(42)) +* return yield* Fiber.join(fiber) +* }) +* +* const actual = await Effect.runPromise(program) +* actual // => 42 +* ``` +* +* @see {@link await_ await} for inspecting the fiber outcome as an Exit +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const join = fiberJoin; +// main.js +const Store = Service("test/RealRetainedFiber"); +const readHelper = () => "read"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + return Store.of({ readOne }); +})); +let retained; +const program = gen(function* () { + const fiber = yield* forkChild(gen(function* () { + return (yield* Store).readOne(); + })); + retained = fiber; + return yield* join(fiber); +}); +assert.strictEqual(await runPromise(provide(program, StoreLayer)), "read"); +assert.ok(retained !== void 0); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/main.js new file mode 100644 index 000000000000..36eae3b6ed31 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/retained_fiber/main.js @@ -0,0 +1,35 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Fiber from "effect/Fiber" + +// A forked and joined Fiber, kept after its scope ends, cannot observe a +// service, so the pass must still remove `writeOne`. +const Store = Context.Service("test/RealRetainedFiber") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +let retained +const program = Effect.gen(function* () { + const fiber = yield* Effect.forkChild( + Effect.gen(function* () { + return (yield* Store).readOne() + }) + ) + retained = fiber + return yield* Fiber.join(fiber) +}) + +assert.strictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), "read") +assert.ok(retained !== undefined) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/_config.json new file mode 100644 index 000000000000..1b5590ca2123 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/_config.json @@ -0,0 +1,8 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + } +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/_test.mjs new file mode 100644 index 000000000000..a698a820f53d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/_test.mjs @@ -0,0 +1,15 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["readHelper", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/artifacts.snap new file mode 100644 index 000000000000..9b51267d6c32 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/artifacts.snap @@ -0,0 +1,4616 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealRunOptions"); +const readHelper = () => "read"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + return Store.of({ readOne }); +})); +const program = gen(function* () { + return (yield* Store).readOne(); +}); +let started = 0; +const result = await runPromise(provide(program, StoreLayer), { onFiberStart: () => { + started++; +} }); +assert.strictEqual(result, "read"); +assert.ok(started >= 0); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/main.js new file mode 100644 index 000000000000..6c4a39a78b20 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/run_options/main.js @@ -0,0 +1,33 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// RunOptions with an `onFiberStart` that ignores the Fiber cannot observe a +// service, so the pass must still remove `writeOne`. +const Store = Context.Service("test/RealRunOptions") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +const program = Effect.gen(function* () { + return (yield* Store).readOne() +}) + +let started = 0 +const result = await Effect.runPromise(Effect.provide(program, StoreLayer), { + onFiberStart: () => { + started++ + } +}) +assert.strictEqual(result, "read") +assert.ok(started >= 0) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/_test.mjs new file mode 100644 index 000000000000..790242d46c8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The pass is turned off: every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/artifacts.snap new file mode 100644 index 000000000000..7db1ba944e32 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/artifacts.snap @@ -0,0 +1,4682 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Context.getOrUndefinedUnsafe` reads Context internals at 23:28 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const context$1 = () => getContext; +const getContext = /*#__PURE__*/ withFiber((fiber) => succeed(fiber.context)); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Returns the complete context. +* +* **When to use** +* +* Use to read the complete `Context` available to the current effect. +* +* **Details** +* +* This function allows you to access all services that are currently available +* in the effect's environment. This can be useful for debugging, introspection, +* or when you need to pass the entire context to another function. +* +* **Example** (Reading the full context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Option } from "effect" +* const output: Array = [] +* +* const Logger = Context.Service<{ +* log: (msg: string) => void +* }>("Logger") +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* const program = Effect.gen(function*() { +* const allServices = yield* Effect.context() +* +* // Check if specific services are available +* const loggerOption = Context.getOption(allServices, Logger) +* const databaseOption = Context.getOption(allServices, Database) +* +* yield* Effect.sync(() => { output.push(`Logger available: ${Option.isSome(loggerOption)}`) }) +* yield* Effect.sync(() => { output.push(`Database available: ${Option.isSome(databaseOption)}`) }) +* }) +* +* const context = Context.make(Logger, { log: () => {} }) +* .pipe(Context.add(Database, { query: () => "result" })) +* +* const provided = Effect.provideContext(program, context) +* Effect.runSync(provided) +* output // => ["Logger available: true", "Database available: true"] +* ``` +* +* @see {@link contextWith} for deriving an effect from the complete context +* @see {@link service} for reading one service from the context +* +* @stability stable +* @category accessors +* @since 2.0.0 +*/ +const context = context$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealGetOrUndefinedUnsafe"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const program = gen(function* () { + const store = yield* Store; + const context$2 = yield* context(); + return [store.readOne(), getOrUndefinedUnsafe(context$2, "test/RealGetOrUndefinedUnsafe").unused()]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "unused"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/main.js new file mode 100644 index 000000000000..6627354407dd --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_get_or_undefined_unsafe/main.js @@ -0,0 +1,26 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// `Context.getOrUndefinedUnsafe` looks a service up by its key string. +const Store = Context.Service("test/RealGetOrUndefinedUnsafe") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + const context = yield* Effect.context() + return [store.readOne(), Context.getOrUndefinedUnsafe(context, "test/RealGetOrUndefinedUnsafe").unused()] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "unused"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/_test.mjs new file mode 100644 index 000000000000..790242d46c8d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/_test.mjs @@ -0,0 +1,12 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// The pass is turned off: every method stays. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["unused", "unusedHelper"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/artifacts.snap new file mode 100644 index 000000000000..e5738c00c40a --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/artifacts.snap @@ -0,0 +1,4624 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## EFFECT_SERVICE_SHAKING + +```text +[EFFECT_SERVICE_SHAKING] [bailout] `Context.makeUnsafe` reads Context internals at 22:35 in main.js + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealMakeUnsafe"); +const unusedHelper = () => "unused"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => "read"; + const unused = () => unusedHelper(); + return Store.of({ + readOne, + unused + }); +})); +const program = gen(function* () { + return [(yield* Store).readOne(), typeof makeUnsafe$2(/* @__PURE__ */ new Map())]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "object"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/main.js new file mode 100644 index 000000000000..48702f2a6bd5 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/string_key_make_unsafe/main.js @@ -0,0 +1,25 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" + +// `Context.makeUnsafe` builds a Context from a map keyed by strings. +const Store = Context.Service("test/RealMakeUnsafe") + +const unusedHelper = () => "unused" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => "read" + const unused = () => unusedHelper() + return Store.of({ readOne, unused }) + }) +) + +const program = Effect.gen(function* () { + const store = yield* Store + return [store.readOne(), typeof Context.makeUnsafe(new Map())] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "object"]) diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/_config.json b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/_config.json new file mode 100644 index 000000000000..11f1928e8f09 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/_config.json @@ -0,0 +1,9 @@ +{ + "_comment": "Uses the real effect package from the repository devDependencies.", + "config": { + "experimental": { + "effectServiceShaking": true + } + }, + "extendedTests": false +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/_test.mjs b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/_test.mjs new file mode 100644 index 000000000000..a698a820f53d --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/_test.mjs @@ -0,0 +1,15 @@ +import assert from "node:assert" +import fs from "node:fs" +import path from "node:path" + +// The program asserts its own output when imported. +await import("./dist/main.js") + +// Positive gate: the pass must actually remove code here. +const code = fs.readFileSync(path.join(import.meta.dirname, "dist/main.js"), "utf8") +for (const name of ["writeHelper", "writeOne"]) { + assert.doesNotMatch(code, new RegExp(`\\b${name}\\b`), `${name} should be removed`) +} +for (const name of ["readHelper", "readOne"]) { + assert.match(code, new RegExp(`\\b${name}\\b`), `${name} should be kept`) +} diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/artifacts.snap b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/artifacts.snap new file mode 100644 index 000000000000..af832d8d6389 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/artifacts.snap @@ -0,0 +1,4627 @@ +--- +source: crates/rolldown_testing/src/integration_test.rs +--- +# warnings + +## UNRESOLVED_IMPORT + +```text +[UNRESOLVED_IMPORT] Could not resolve 'node:vm' in main.js + ╭─[ main.js:5:33 ] + │ + 5 │ import { compileFunction } from "node:vm" + │ ────┬──── + │ ╰────── Module not found, treating it as an external dependency +───╯ + +``` + +# Assets + +## main.js + +```js +import assert from "node:assert"; +import { compileFunction } from "node:vm"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Pipeable.js +/** +* The `Pipeable` module defines the shared interface and implementation helpers +* for values that support Effect-style method chaining with `.pipe(...)`. +* +* A `Pipeable` value can pass itself through a sequence of unary functions from +* left to right, so code can be written as `value.pipe(f, g, h)` instead of +* deeply nesting calls. This is the method form used by many Effect data types +* to compose transformations, validations, and effectful operations while +* keeping the original value as the starting point of the pipeline. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Applies a `pipe` method's variadic arguments to an initial value from left +* to right. +* +* **When to use** +* +* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` +* object. +* +* **Details** +* +* This helper is intended for implementing `Pipeable.pipe` methods that +* receive JavaScript's `arguments` object. With no functions it returns the +* original value; otherwise it feeds each result into the next function. +* +* **Example** (Implementing a pipe method) +* +* ```ts import.meta.vitest +* import { Pipeable } from "effect" +* +* class NumberBox { +* constructor(readonly value: number) {} +* +* pipe(..._fns: ReadonlyArray<(value: number) => number>): number { +* return Pipeable.pipeArguments(this.value, arguments) as number +* } +* } +* +* const result = new NumberBox(5).pipe( +* (n) => n + 2, +* (n) => n * 3 +* ) +* result // => 21 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const pipeArguments = (self, args) => { + switch (args.length) { + case 0: return self; + case 1: return args[0](self); + case 2: return args[1](args[0](self)); + case 3: return args[2](args[1](args[0](self))); + case 4: return args[3](args[2](args[1](args[0](self)))); + case 5: return args[4](args[3](args[2](args[1](args[0](self))))); + case 6: return args[5](args[4](args[3](args[2](args[1](args[0](self)))))); + case 7: return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))); + case 8: return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))); + case 9: return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))))); + default: { + let ret = self; + for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret); + return ret; + } + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Function.js +/** +* Creates a function that can be called in data-first style or data-last +* (`pipe`-friendly) style. +* +* **When to use** +* +* Use to expose one implementation through both direct and `pipe`-friendly +* call styles. +* +* **Details** +* +* Pass either the arity of the uncurried function or a predicate that decides +* whether the current call is data-first. Arity is the common case. Use a +* predicate when optional arguments make arity ambiguous. +* +* **Example** (Selecting data-first or data-last style by arity) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >(2, (self, that) => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Defining overloads with call signatures) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum: { +* (that: number): (self: number) => number +* (self: number, that: number): number +* } = Function.dual(2, (self: number, that: number): number => self + that) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* **Example** (Selecting data-first or data-last style with a predicate) +* +* ```ts import.meta.vitest +* import { Function, pipe } from "effect" +* +* const sum = Function.dual< +* (that: number) => (self: number) => number, +* (self: number, that: number) => number +* >( +* (args) => args.length === 2, +* (self, that) => self + that +* ) +* +* sum(2, 3) // => 5 +* pipe(2, sum(3)) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const dual = function(arity, body) { + if (typeof arity === "function") return function() { + return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments); + }; + switch (arity) { + case 0: + case 1: throw new RangeError(`Invalid arity ${arity}`); + case 2: return function(a, b) { + if (arguments.length >= 2) return body(a, b); + return function(self) { + return body(self, a); + }; + }; + case 3: return function(a, b, c) { + if (arguments.length >= 3) return body(a, b, c); + return function(self) { + return body(self, a, b); + }; + }; + default: return function() { + if (arguments.length >= arity) return body.apply(this, arguments); + const args = arguments; + return function(self) { + return body(self, ...args); + }; + }; + } +}; +/** +* Returns its input argument unchanged. +* +* **When to use** +* +* Use to return a value unchanged where a function is required. +* +* **Example** (Returning the same value) +* +* ```ts import.meta.vitest +* import { identity } from "effect" +* +* identity(5) // => 5 +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const identity = (a) => a; +/** +* Creates a zero-argument function that always returns the provided value. +* +* **When to use** +* +* Use when you need a thunk or callback that returns the same value on every +* invocation. +* +* **Example** (Creating a constant thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* const constNull = Function.constant(null) +* +* constNull() // => null +* constNull() // => null +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const constant = (value) => () => value; +/** +* Returns `true` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `true` on every invocation. +* +* **Example** (Returning true from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constTrue() // => true +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constTrue = /*#__PURE__*/ constant(true); +/** +* Returns `undefined` when called. +* +* **When to use** +* +* Use when you need a thunk that returns `undefined` on every invocation. +* +* **Example** (Returning undefined from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constUndefined() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constUndefined = /*#__PURE__*/ constant(void 0); +/** +* Returns no meaningful value when called. +* +* **When to use** +* +* Use when you need a thunk that is called only for its effect and has no +* meaningful return value. +* +* **Example** (Returning void from a thunk) +* +* ```ts import.meta.vitest +* import { Function } from "effect" +* +* Function.constVoid() // => undefined +* ``` +* +* @stability stable +* @category constants +* @since 2.0.0 +*/ +const constVoid = constUndefined; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/equal.js +/** @internal */ +const getAllObjectKeys = (obj) => { + const keys = new Set(Reflect.ownKeys(obj)); + if (obj.constructor === Object) return keys; + if (obj instanceof Error) keys.delete("stack"); + const proto = Object.getPrototypeOf(obj); + let current = proto; + while (current !== null && current !== Object.prototype) { + const ownKeys = Reflect.ownKeys(current); + for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]); + current = Object.getPrototypeOf(current); + } + if (keys.has("constructor") && typeof obj.constructor === "function" && proto === obj.constructor.prototype) keys.delete("constructor"); + return keys; +}; +/** @internal */ +const byReferenceInstances = /*#__PURE__*/ new WeakSet(); +/** @internal */ +const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength); +/** @internal */ +const isArrayBufferLike = (u) => u instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer; +/** +* Returns `undefined` for detached buffers, which can no longer be read. +* +* @internal +*/ +const bufferBytes = (buffer) => { + try { + return new Uint8Array(buffer); + } catch { + return; + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/hash.js +/** +* Back-edge count used to avoid caching entry-point-dependent hashes. +* +* @internal +*/ +let backEdges = 0; +/** @internal */ +const addBackEdge = () => { + backEdges++; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Predicate.js +/** +* Defines runtime checks for values. +* +* A `Predicate` returns `true` or `false` for an `A`. A +* `Refinement` is a predicate that also narrows the TypeScript type when +* it succeeds. This module includes guards for common JavaScript values, +* property and tag checks, tuple and struct checks, boolean combinators, and +* helpers for composing predicates and refinements. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Checks whether a value is a `function`. +* +* **When to use** +* +* Use when you need a `Predicate` guard to narrow an `unknown` value to a +* callable function. +* +* **Details** +* +* Uses `typeof input === "function"`. +* +* **Example** (Guarding functions) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const data: unknown = () => 1 +* +* if (Predicate.isFunction(data)) { +* data() // => 1 +* } +* ``` +* +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +function isFunction(input) { + return typeof input === "function"; +} +/** +* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). +* +* **When to use** +* +* Use when you need a `Predicate` guard that accepts arrays and functions as +* well as objects. +* +* **Details** +* +* Returns `true` for arrays and functions, and `false` for `null`. +* +* **Example** (Checking object keywords) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* Predicate.isObjectKeyword(() => 1) // => true +* Predicate.isObjectKeyword(null) // => false +* ``` +* +* @see {@link isObject} +* @see {@link isObjectOrArray} +* @stability stable +* @category guards +* @since 4.0.0 +*/ +function isObjectKeyword(input) { + return typeof input === "object" && input !== null || isFunction(input); +} +/** +* Checks whether a value has a given property key. +* +* **When to use** +* +* Use when you need a `Predicate` guard for property access on `unknown` +* values with a simple structural object check. +* +* **Details** +* +* Uses the `in` operator and `isObjectKeyword`. This does not check property +* value types. +* +* **Example** (Guarding object properties) +* +* ```ts import.meta.vitest +* import { Predicate } from "effect" +* +* const hasName = Predicate.hasProperty("name") +* const data: unknown = { name: "Ada" } +* +* if (hasName(data)) { +* data.name // => "Ada" +* } +* ``` +* +* @see {@link isTagged} +* @see {@link isObjectKeyword} +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const hasProperty = /*#__PURE__*/ dual(2, (self, property) => isObjectKeyword(self) && property in self); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Hash.js +/** +* Computes Effect hash values and defines the interface for objects that want +* to provide their own hash implementation. Hashes are small numeric +* fingerprints used by Effect data structures to bucket values quickly; they +* are not cryptographic digests and they are not proof that two values are +* equal. The module also includes helpers for primitive, structure, array, and +* reference-based hashes, plus functions for combining and optimizing numeric +* hash values. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Defines the unique identifier used to identify objects that implement the Hash interface. +* +* **When to use** +* +* Use as the computed property key for the method that supplies a custom hash +* value on a `Hash` implementor. +* +* @see {@link Hash} for the interface implemented with this symbol +* @see {@link isHash} for checking whether a value implements `Hash` +* @see {@link hash} for computing hash values +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol$1 = "~effect/Hash"; +/** +* Computes a hash value for any given value. +* +* **When to use** +* +* Use to compute an Effect hash for primitives, collections, and hashable +* objects. +* +* **Details** +* +* This function can hash primitives (numbers, strings, booleans, etc.) as well as +* objects, arrays, and other complex data structures. It automatically handles +* different types and provides a consistent hash value for equivalent inputs. +* +* **Gotchas** +* +* Objects being hashed must be treated as immutable after their first hash +* computation. Hash results are cached, so mutating an object after hashing will +* lead to stale cached values and broken hash-based operations. For mutable +* objects, implement a custom `Hash` interface that hashes the object reference +* rather than its content. +* +* **Example** (Hashing different values) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.hash(42) === Hash.hash(42) // => true +* Hash.hash("hello") === Hash.hash("hello") // => true +* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const hash = (self) => { + switch (typeof self) { + case "number": return number(self); + case "bigint": return string(self.toString(10)); + case "string": return string(self); + case "function": + case "object": if (self === null) break; + else if (self instanceof Date) { + if (Number.isNaN(self.getTime())) return string("Invalid Date"); + return string(self.toISOString()); + } else if (self instanceof RegExp) return string(self.toString()); + else { + if (byReferenceInstances.has(self)) return random(self); + const cached = hashCache.get(self); + if (cached !== void 0) return cached; + if (visitedObjects.has(self)) { + addBackEdge(); + return string("[Circular]"); + } + visitedObjects.add(self); + const seen = backEdges; + let h; + try { + if (isHash(self)) h = self[symbol$1](); + else if (typeof self === "function") h = random(self); + else if (isArrayBufferLike(self)) { + const bytes = bufferBytes(self); + h = bytes === void 0 ? random(self) : array(bytes); + } else if (self instanceof DataView) h = array(viewBytes(self)); + else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self); + else if (self instanceof Map) h = hashMap(self); + else if (self instanceof Set) h = hashSet(self); + else h = structure(self); + } finally { + visitedObjects.delete(self); + } + if (seen === backEdges) hashCache.set(self, h); + return h; + } + } + return optimize(mix(string(String(self)))); +}; +/** +* Generates a random hash value for an object and caches it. +* +* **When to use** +* +* Use to hash an object by reference identity instead of structural content. +* +* **Details** +* +* This function creates a random hash value for objects that don't have their own +* hash implementation. The hash value is cached using a WeakMap, so the same object +* will always return the same hash value during its lifetime. +* +* **Example** (Hashing objects by reference) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { a: 1 } +* const obj2 = { a: 1 } +* +* Hash.random(obj1) === Hash.random(obj1) // => true +* +* typeof Hash.random(obj2) // => "number" +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const random = (self) => { + if (!randomHashCache.has(self)) randomHashCache.set(self, optimize(Math.random() * 4294967296 | 0)); + return randomHashCache.get(self); +}; +const mix = (h) => { + h ^= h >>> 16; + h = Math.imul(h, 2246822507); + h ^= h >>> 13; + h = Math.imul(h, 3266489909); + return h ^ h >>> 16; +}; +/** +* Combines two hash values into a single hash value. +* +* **When to use** +* +* Use to build a hash for a composite value by folding together hash values for +* its parts. +* +* **Details** +* +* Supports direct and pipeable usage. Argument order affects the result. +* +* **Example** (Combining hash values) +* +* ```ts import.meta.vitest +* import { Hash, pipe } from "effect" +* +* const hash1 = Hash.hash("hello") +* const hash2 = Hash.hash("world") +* +* const combined = Hash.combine(hash2)(hash1) +* combined === pipe(hash1, Hash.combine(hash2)) // => true +* ``` +* +* @see {@link hash} for computing hash values from arbitrary inputs +* @see {@link structureKeys} for hashing selected object fields without manual combination +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const combine = /*#__PURE__*/ dual(2, (self, b) => mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507))); +/** +* Applies bit manipulation techniques to optimize a hash value. +* +* **When to use** +* +* Use to improve the bit distribution of a raw numeric hash value. +* +* **Details** +* +* This function takes a hash value and applies bitwise operations to improve +* the distribution of hash values, reducing the likelihood of collisions. +* +* **Example** (Optimizing a hash value) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.optimize(1234567890) // => 160826066 +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824; +/** +* Checks whether a value implements the Hash interface. +* +* **When to use** +* +* Use to detect whether an unknown value provides a custom hash implementation. +* +* **Details** +* +* This function determines whether a given value has a function under the Hash +* symbol, indicating that it can provide its own hash value implementation. +* Data that merely carries the key, such as parsed JSON, is hashed as data. +* +* **Example** (Checking for Hash support) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* class MyHashable implements Hash.Hash { +* [Hash.symbol]() { +* return 42 +* } +* } +* +* Hash.isHash(new MyHashable()) // => true +* Hash.isHash({}) // => false +* Hash.isHash("string") // => false +* ``` +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isHash = (u) => hasProperty(u, "~effect/Hash") && typeof u["~effect/Hash"] === "function"; +const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8)); +/** +* Computes a hash value for a number. +* +* **When to use** +* +* Use to hash a JavaScript number with Effect's numeric hash semantics. +* +* **Details** +* +* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits, +* with a canonical representation for `NaN`. +* +* **Example** (Hashing numbers) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Number.isInteger(Hash.number(42)) // => true +* Number.isInteger(Hash.number(3.14)) // => true +* Hash.number(NaN) === Hash.number(NaN) // => true +* Hash.number(Infinity) === Hash.number(Infinity) // => true +* Hash.number(100) === Hash.number(100) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const number = (n) => { + const h = n | 0; + if (h === n) return optimize(h); + float64.setFloat64(0, n !== n ? NaN : n); + return optimize(combine(float64.getInt32(0), float64.getInt32(4))); +}; +/** +* Computes a hash value for a string using the djb2 algorithm. +* +* **When to use** +* +* Use when you need a string field to contribute to a custom structural hash +* implementation. +* +* **Details** +* +* This function implements a variation of the djb2 hash algorithm, which is +* known for its good distribution properties and speed. It processes each +* character of the string to produce a consistent hash value. +* +* **Example** (Hashing strings) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* Hash.string("hello") // => 181380007 +* Hash.string("world") // => 164394279 +* Hash.string("") // => 5381 +* Hash.string("test") === Hash.string("test") // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const string = (str) => { + let h = 5381, i = str.length; + while (i) h = h * 33 ^ str.charCodeAt(--i); + return optimize(h); +}; +/** +* Computes a hash value for an object using only the specified keys. +* +* **When to use** +* +* Use to hash an object by a selected set of property keys. +* +* **Details** +* +* This function allows you to hash an object by considering only specific keys, +* which is useful when you want to create a hash based on a subset of an object's +* properties. +* +* **Example** (Hashing selected object keys) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const person = { name: "John", age: 30, city: "New York" } +* +* const hash1 = Hash.structureKeys(person, ["name", "age"]) +* const hash2 = Hash.structureKeys(person, ["name", "city"]) +* +* hash1 // => -731887653 +* hash2 // => 148523102 +* +* const person2 = { name: "John", age: 30, city: "Boston" } +* const hash3 = Hash.structureKeys(person2, ["name", "age"]) +* hash1 === hash3 // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structureKeys = (o, keys) => { + let h = 12289; + for (const key of keys) h ^= combine(hash(key), hash(o[key])); + return optimize(h); +}; +/** +* Computes a structural hash for an object using Effect's object key collection. +* +* **When to use** +* +* Use to hash an object from all structural keys collected by Effect. +* +* **Details** +* +* The hash is based on the object's structural keys and their values, including +* symbol keys and relevant prototype keys for non-plain objects. +* +* **Example** (Hashing object structures) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const obj1 = { name: "John", age: 30 } +* const obj2 = { name: "Jane", age: 25 } +* const obj3 = { name: "John", age: 30 } +* +* Hash.structure(obj1) // => -731887653 +* Hash.structure(obj2) // => -222100417 +* Hash.structure(obj3) // => -731887653 +* Hash.structure(obj1) === Hash.structure(obj3) // => true +* ``` +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const structure = (o) => structureKeys(o, getAllObjectKeys(o)); +const unordered = (seed, f) => (iter) => { + let h = seed; + for (const element of iter) h ^= f(element); + return optimize(h); +}; +/** +* Computes a hash value for an iterable by hashing all of its elements. +* +* **When to use** +* +* Use to hash the values yielded by an iterable with Effect hash semantics. +* +* **Details** +* +* Folds element hashes with {@link combine}, so order and length affect the +* result. +* +* **Gotchas** +* +* A hash is not an equality proof. Distinct inputs can still share a hash. +* +* **Example** (Hashing arrays) +* +* ```ts import.meta.vitest +* import { Hash } from "effect" +* +* const arr1 = [1, 2, 3] +* const arr2 = [1, 2, 3] +* const arr3 = [3, 2, 1] +* +* Hash.array(arr1) === Hash.array(arr2) // => true +* Hash.array(arr1) === Hash.array(arr3) // => false +* ``` +* +* @see {@link hash} for the general-purpose hash dispatcher +* +* @stability stable +* @category hashing +* @since 2.0.0 +*/ +const array = (arr) => { + let h = 6151; + for (const element of arr) h = combine(h, hash(element)); + return optimize(h); +}; +const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string("Map"), ([k, v]) => combine(hash(k), hash(v))); +const setSeed = /*#__PURE__*/ string("Set"); +const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element))); +const randomHashCache = /*#__PURE__*/ new WeakMap(); +const hashCache = /*#__PURE__*/ new WeakMap(); +const visitedObjects = /*#__PURE__*/ new WeakSet(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Equal.js +/** +* Defines the unique string identifier for the `Equal` interface. +* +* **When to use** +* +* Use when you implement custom equality and need the computed property key for +* the equality method. +* +* **Details** +* +* This is a pure constant with no allocation or side effects. +* +* **Example** (Implementing Equal on a class) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class UserId implements Equal.Equal { +* constructor(readonly id: string) {} +* +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof UserId && this.id === that.id +* } +* +* [Hash.symbol](): number { +* return Hash.string(this.id) +* } +* } +* +* Equal.equals(new UserId("1"), new UserId("1")) // => true +* Equal.equals(new UserId("1"), new UserId("2")) // => false +* ``` +* +* @see {@link Equal} — the interface that uses this symbol +* @see {@link isEqual} — type guard for `Equal` implementors +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const symbol = "~effect/Equal"; +function equals() { + if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]); + return compareBoth(arguments[0], arguments[1]); +} +function compareBoth(self, that) { + if (self === that) return true; + if (self == null || that == null) return false; + const selfType = typeof self; + if (selfType !== typeof that) return false; + if (selfType === "number" && self !== self && that !== that) return true; + if (selfType !== "object" && selfType !== "function") return false; + if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false; + return compareObjects(self, that); +} +function compareObjects(self, that) { + const depth = pathLeft.length; + for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true; + if (depth) return compareOnPath(self, that); + let known = results.get(self); + if (!known) results.set(self, known = /* @__PURE__ */ new WeakMap()); + let result = known.get(that); + if (result === void 0) known.set(that, result = compareOnPath(self, that)); + return result; +} +function compareOnPath(self, that) { + pathLeft.push(self); + pathRight.push(that); + try { + return compareStructure(self, that); + } finally { + pathLeft.pop(); + pathRight.pop(); + } +} +const pathLeft = []; +const pathRight = []; +const results = /*#__PURE__*/ new WeakMap(); +function compareStructure(self, that) { + if (hash(self) !== hash(that)) return false; + else if (self instanceof Date) { + if (!(that instanceof Date)) return false; + const selfTime = self.getTime(); + const thatTime = that.getTime(); + return selfTime === thatTime || Number.isNaN(selfTime) && Number.isNaN(thatTime); + } else if (self instanceof RegExp) return that instanceof RegExp && self.toString() === that.toString(); + const bothEquals = isEqual(self); + if (bothEquals !== isEqual(that) || typeof self === "function" && !bothEquals) return false; + else if (bothEquals) return self[symbol](that); + else if (Array.isArray(self)) { + if (!Array.isArray(that) || self.length !== that.length) return false; + return compareArrays(self, that); + } else if (isArrayBufferLike(self)) { + if (!isArrayBufferLike(that) || self instanceof ArrayBuffer !== that instanceof ArrayBuffer) return false; + const selfBytes = bufferBytes(self); + const thatBytes = bufferBytes(that); + return selfBytes !== void 0 && thatBytes !== void 0 && compareTypedArrays(selfBytes, thatBytes); + } else if (ArrayBuffer.isView(self)) { + const selfIsDataView = self instanceof DataView; + if (!ArrayBuffer.isView(that) || self.byteLength !== that.byteLength || selfIsDataView !== that instanceof DataView) return false; + if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that)); + return compareTypedArrays(self, that); + } else if (self instanceof Map) { + if (!(that instanceof Map) || self.size !== that.size) return false; + return compareHashed(self, that, entryHash, equalEntries); + } else if (self instanceof Set) { + if (!(that instanceof Set) || self.size !== that.size) return false; + return compareHashed(self, that, hash, compareBoth); + } + return compareRecords(self, that); +} +function compareArrays(self, that) { + for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false; + return true; +} +function compareTypedArrays(self, that) { + if (self.length !== that.length) return false; + for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false; + return true; +} +function compareRecords(self, that) { + const selfKeys = getAllObjectKeys(self); + const thatKeys = getAllObjectKeys(that); + if (selfKeys.size !== thatKeys.size) return false; + for (const key of selfKeys) if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false; + return true; +} +function compareHashed(self, that, hashOf, equivalent) { + const groups = /* @__PURE__ */ new Map(); + let remaining = 0; + for (const item of that) { + const h = hashOf(item); + const group = groups.get(h); + if (group) group.push(item); + else groups.set(h, [item]); + remaining++; + } + outer: for (const item of self) { + const group = groups.get(hashOf(item)); + if (group) { + for (let i = 0; i < group.length; i++) if (equivalent(item, group[i])) { + group[i] = group[group.length - 1]; + group.pop(); + remaining--; + continue outer; + } + } + return false; + } + return remaining === 0; +} +const entryHash = (entry) => hash(entry[0]); +const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]); +/** +* Checks whether a value implements the {@link Equal} interface. +* +* **When to use** +* +* Use when you need generic utility code to distinguish `Equal` implementors +* from plain values before calling `[Equal.symbol]` directly. +* +* **Details** +* +* - Pure function, no side effects. +* - Returns `true` if and only if `u` has a function keyed by {@link symbol}. +* Data that merely carries the key, such as parsed JSON, is not `Equal`. +* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. +* +* **Example** (Checking Equal values) +* +* ```ts import.meta.vitest +* import { Equal, Hash } from "effect" +* +* class Token implements Equal.Equal { +* constructor(readonly value: string) {} +* [Equal.symbol](that: Equal.Equal): boolean { +* return that instanceof Token && this.value === that.value +* } +* [Hash.symbol](): number { +* return Hash.string(this.value) +* } +* } +* +* Equal.isEqual(new Token("abc")) // => true +* Equal.isEqual({ x: 1 }) // => false +* Equal.isEqual(42) // => false +* ``` +* +* @see {@link Equal} — the interface being checked +* @see {@link symbol} — the property key that signals `Equal` support +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isEqual = (u) => hasProperty(u, "~effect/Equal") && typeof u["~effect/Equal"] === "function"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Redactable.js +/** +* Defines the symbol used to identify objects that implement the {@link Redactable} +* protocol. +* +* **When to use** +* +* Use as the property key when implementing the `Redactable` protocol. +* +* **Details** +* +* Add a method under this key to make an object redactable. The method receives +* the current `Context` and must return the replacement value. The symbol is +* registered globally via `Symbol.for("~effect/Redactable")`, so it is +* identical across multiple copies of the library at runtime. +* +* **Example** (Masking an API key) +* +* ```ts import.meta.vitest +* import { Context, Redactable } from "effect" +* +* class ApiKey { +* constructor(readonly raw: string) {} +* +* [Redactable.symbolRedactable](_ctx: Context.Context) { +* return this.raw.slice(0, 4) + "..." +* } +* } +* +* Redactable.redact(new ApiKey("secret-key")) // => "secr..." +* ``` +* +* @see {@link Redactable} for the interface this symbol belongs to +* @see {@link isRedactable} to check whether a value has this symbol +* @stability stable +* @category symbols +* @since 3.10.0 +*/ +const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable"); +/** +* Returns the result of calling `[symbolRedactable]` on a value that is +* already known to be {@link Redactable}. +* +* **When to use** +* +* Use when you need to read the redacted representation from a value already +* verified as `Redactable`. +* +* **Details** +* +* This function reads the current fiber's `Context` from the global fiber +* reference and passes it to the redaction method. +* +* **Gotchas** +* +* If no fiber is active, an empty `Context` is passed to the redaction method. +* +* @see {@link redact} for the higher-level variant that handles non-redactable values +* @see {@link isRedactable} for the type guard to verify before calling this +* @stability stable +* @category destructors +* @since 4.0.0 +*/ +function getRedacted(redactable) { + return redactable[symbolRedactable](globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1); +} +/** @internal */ +const currentFiberTypeId = "~effect/Fiber/currentFiber"; +const emptyMap = /*#__PURE__*/ new Map(); +const emptyContext$1 = { + "~effect/Context": {}, + base: emptyMap, + depth: 0, + mapUnsafe: emptyMap, + pipe() { + return pipeArguments(this, arguments); + } +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Formatter.js +/** +* Formats JavaScript values into readable strings. +* +* `format` is intended for logs, diagnostics, and error messages. It handles +* primitives, objects, arrays, dates, regular expressions, maps, sets, class +* instances, errors, circular references, and redactable values. `formatJson` +* wraps JSON formatting with redaction and circular-reference handling, and the +* module also includes helpers for property keys, paths, and dates. +* +* @stability stable +* @since 4.0.0 +*/ +/** +* Converts any JavaScript value into a human-readable string. +* +* **When to use** +* +* Use when you need to format arbitrary JavaScript values for debugging, +* logging, or error messages. +* +* **Details** +* +* - Output is **not** valid JSON; use {@link formatJson} when you need +* parseable JSON. +* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class +* instances that `JSON.stringify` cannot represent. +* - Circular references are shown as `"[Circular]"` instead of throwing. +* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing. +* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). +* Strings are JSON-quoted. +* - Objects with a custom `toString` (not `Object.prototype.toString`): +* `toString()` is called unless `ignoreToString` is `true`. +* - Errors with a `cause`: formatted as `" (cause: )"`. +* - Iterables (`Set`, `Map`, etc.): formatted as +* `ClassName([...elements])`. +* - Class instances: wrapped as `ClassName({...})`. +* - `Redactable` values are automatically redacted. +* - Arrays/objects with 0–1 entries are inline; larger ones are +* pretty-printed when `space` is set. +* - `space` — indentation unit (number of spaces, or a string like +* `"\t"`). Defaults to `0` (compact). +* - `ignoreToString` — skip calling `toString()`. Defaults to `false`. +* +* **Example** (Formatting compact output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}" +* ``` +* +* **Example** (Pretty-printed output) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 }) +* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}" +* ``` +* +* **Example** (Handling circular references) +* +* ```ts import.meta.vitest +* import { Formatter } from "effect" +* +* const obj: any = { name: "loop" } +* obj.self = obj +* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}" +* ``` +* +* @see {@link formatJson} +* @see {@link Formatter} +* @stability stable +* @category formatting +* @since 2.0.0 +*/ +function format(input, options) { + const space = options?.space ?? 0; + const ancestors = /* @__PURE__ */ new WeakSet(); + const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space; + const ind = (d) => gap.repeat(d); + const wrap = (v, body) => { + const ctor = v?.constructor; + return ctor && ctor !== Object.prototype.constructor && ctor.name ? `${ctor.name}(${body})` : body; + }; + const ownKeys = (o) => { + try { + return Reflect.ownKeys(o); + } catch { + return ["[ownKeys threw]"]; + } + }; + function recur(v, d = 0) { + try { + return recurUnsafe(v, d); + } catch { + if (typeof v === "object" && v !== null || typeof v === "function") ancestors.delete(v); + return "[inspection threw]"; + } + } + function recurUnsafe(v, d = 0) { + if (typeof v === "string") return JSON.stringify(v); + if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol") return String(v); + if (typeof v === "bigint") return String(v) + "n"; + if (typeof v === "object" || typeof v === "function") { + if (ancestors.has(v)) return CIRCULAR; + ancestors.add(v); + let output; + if (symbolRedactable in v) output = recur(getRedacted(v), d); + else if (Array.isArray(v)) output = !gap || v.length <= 1 ? `[${v.map((x) => recur(x, d)).join(",")}]` : `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`; + else if (v instanceof Date) output = formatDate(v); + else if (!options?.ignoreToString && hasProperty(v, "toString") && typeof v["toString"] === "function" && v["toString"] !== Object.prototype.toString && v["toString"] !== Array.prototype.toString) { + const s = safeToString(v); + output = v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s; + } else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`; + else { + const keys = ownKeys(v); + if (!gap || keys.length <= 1) { + const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`; + output = wrap(v, body); + } else { + const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`; + output = wrap(v, body); + } + } + ancestors.delete(v); + return output; + } + return String(v); + } + return recur(input, 0); +} +const CIRCULAR = "[Circular]"; +/** +* @internal +*/ +function formatPropertyKey(name) { + return typeof name === "string" ? JSON.stringify(name) : String(name); +} +/** +* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for +* invalid dates instead of throwing. +* +* @internal +*/ +function formatDate(date) { + try { + return date.toISOString(); + } catch { + return "Invalid Date"; + } +} +function safeToString(input) { + try { + const s = input.toString(); + return typeof s === "string" ? s : String(s); + } catch { + return "[toString threw]"; + } +} +function safeGet(input, key) { + try { + return input[key]; + } catch { + return "[property access threw]"; + } +} +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Inspectable.js +/** +* Defines the symbol used by Node.js for custom object inspection. +* +* **When to use** +* +* Use to implement Node.js custom inspection for a value. +* +* **Details** +* +* This symbol is recognized by Node.js's `util.inspect()` function and the REPL +* for custom object representation. When an object has a method with this symbol, +* it will be called to determine how the object should be displayed. +* +* **Example** (Defining custom Node inspection) +* +* ```ts import.meta.vitest +* import { Inspectable } from "effect" +* +* class CustomObject { +* constructor(private value: string) {} +* +* [Inspectable.NodeInspectSymbol]() { +* return `CustomObject(${this.value})` +* } +* } +* +* const obj = new CustomObject("hello") +* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)" +* ``` +* +* @stability stable +* @category symbols +* @since 2.0.0 +*/ +const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom"); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/stackTraceLimit.js +/** +* Check if `Error.stackTraceLimit` is writable. +* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible. +* +* @internal +*/ +const isStackTraceLimitWritable = () => { + const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit"); + if (desc === void 0) return Object.isExtensible(Error); + return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0; +}; +const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable(); +/** +* Get the current `Error.stackTraceLimit` value. +* Returns `undefined` if the property doesn't exist. +* +* @internal +*/ +const getStackTraceLimit = () => Error.stackTraceLimit; +/** +* Safely set `Error.stackTraceLimit` if possible, otherwise no-op. +* +* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be +* restored faithfully. +* +* @internal +*/ +const setStackTraceLimit = (value) => { + if (canWriteStackTraceLimit) Error.stackTraceLimit = value; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Utils.js +/** +* Yields its wrapped value exactly once, then completes with the value sent +* back in. +* +* **When to use** +* +* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be +* `yield*`-ed inside generator functions, such as `Effect.gen` and +* `Option.gen`. +* +* **Details** +* +* The first call to `next()` returns a fresh `{ value: self, done: false }`. +* Every subsequent call returns `{ value: a, done: true }` where `a` is the +* argument passed to `next()`. To keep `yield*` cheap, the completion result +* is the iterator itself rather than a new object, so only the iterator and +* the single yielded result are allocated per `yield*`. +* +* **Example** (Yielding a wrapped value in a generator) +* +* ```ts import.meta.vitest +* import { Utils } from "effect" +* +* const gen = new Utils.SingleShotGen("hello") +* +* gen.next(0).value // => "hello" +* +* gen.next(42).value // => 42 +* ``` +* +* @see {@link Gen} for the type-level signature that relies on `SingleShotGen` +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +var SingleShotGen = class { + constructor(self) { + this.value = self; + this.done = false; + } + /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * + * @since 2.0.0 + */ + next(a) { + if (this.done) { + this.value = a; + return this; + } + this.done = true; + return { + value: this.value, + done: false + }; + } +}; +const pickInternalCall = () => { + const InternalTypeId = "~effect/Utils/internal"; + const standard = { [InternalTypeId]: (body) => { + return body(); + } }; + const forced = { [InternalTypeId]: (body) => { + try { + return body(); + } finally {} + } }; + const limit = getStackTraceLimit(); + if (limit === 0) return forced[InternalTypeId]; + setStackTraceLimit(2); + const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error()); + setStackTraceLimit(limit); + return error.stack?.includes(InternalTypeId) === true ? standard[InternalTypeId] : forced[InternalTypeId]; +}; +/** @internal */ +const internalCall = /*#__PURE__*/ pickInternalCall(); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/core.js +/** @internal */ +const EffectTypeId = `~effect/Effect`; +/** @internal */ +const ExitTypeId = `~effect/Exit`; +const effectVariance = { + _A: identity, + _E: identity, + _R: identity +}; +/** @internal */ +const identifier = `${EffectTypeId}/identifier`; +/** @internal */ +const args = `${EffectTypeId}/args`; +/** @internal */ +const evaluate = `${EffectTypeId}/evaluate`; +/** @internal */ +const contA = `${EffectTypeId}/successCont`; +/** @internal */ +const contE = `${EffectTypeId}/failureCont`; +/** @internal */ +const contAll = `${EffectTypeId}/ensureCont`; +/** @internal */ +const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield"); +/** @internal */ +const PipeInspectableProto = { + pipe() { + return pipeArguments(this, arguments); + }, + toJSON() { + return { ...this }; + }, + toString() { + return format(this.toJSON(), { + ignoreToString: true, + space: 2 + }); + }, + [NodeInspectSymbol]() { + return this.toJSON(); + } +}; +/** @internal */ +const EffectProto = { + [EffectTypeId]: effectVariance, + ...PipeInspectableProto, + [Symbol.iterator]() { + return new SingleShotGen(this); + }, + toJSON() { + return { + _id: "Effect", + op: this[identifier], + ..."~effect/Effect/args" in this ? { args: this[args] } : void 0 + }; + } +}; +/** @internal */ +const isEffect = (u) => hasProperty(u, EffectTypeId); +/** @internal */ +const isExit = (u) => hasProperty(u, ExitTypeId); +/** @internal */ +const CauseTypeId = "~effect/Cause"; +/** @internal */ +const CauseReasonTypeId = "~effect/Cause/Reason"; +/** @internal */ +const isCause = (self) => hasProperty(self, CauseTypeId); +/** @internal */ +var CauseImpl = class { + constructor(failures) { + this[CauseTypeId] = CauseTypeId; + this.reasons = failures; + } + pipe() { + return pipeArguments(this, arguments); + } + toJSON() { + return { + _id: "Cause", + reasons: this.reasons.map((f) => f.toJSON()) + }; + } + toString() { + return `Cause(${format(this.reasons)})`; + } + [NodeInspectSymbol]() { + return this.toJSON(); + } + [symbol](that) { + return isCause(that) && this.reasons.length === that.reasons.length && this.reasons.every((e, i) => equals(e, that.reasons[i])); + } + [symbol$1]() { + return array(this.reasons); + } +}; +const annotationsMap = /*#__PURE__*/ new WeakMap(); +/** @internal */ +var ReasonBase = class { + [CauseReasonTypeId]; + annotations; + _tag; + constructor(_tag, annotations, originalError) { + this[CauseReasonTypeId] = CauseReasonTypeId; + this._tag = _tag; + if (annotations !== constEmptyAnnotations && typeof originalError === "object" && originalError !== null && annotations.size > 0) { + const prevAnnotations = annotationsMap.get(originalError); + if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]); + annotationsMap.set(originalError, annotations); + } + this.annotations = annotations; + } + annotate(annotations, options) { + if (annotations.mapUnsafe.size === 0) return this; + const newAnnotations = new Map(this.annotations); + annotations.mapUnsafe.forEach((value, key) => { + if (options?.overwrite !== true && newAnnotations.has(key)) return; + newAnnotations.set(key, value); + }); + if (options?.overwrite !== true && newAnnotations.size === this.annotations.size) return this; + const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + self.annotations = newAnnotations; + return self; + } + pipe() { + return pipeArguments(this, arguments); + } + toString() { + return format(this); + } + [NodeInspectSymbol]() { + return this.toString(); + } +}; +/** @internal */ +const constEmptyAnnotations = /*#__PURE__*/ new Map(); +/** @internal */ +const causeFromReasons = (reasons) => new CauseImpl(reasons); +const dedupeReasons = (self, that) => { + const buckets = /* @__PURE__ */ new Map(); + const out = []; + for (const reason of self.concat(that)) { + const hash$2 = hash(reason); + const bucket = buckets.get(hash$2); + if (bucket === void 0) buckets.set(hash$2, [reason]); + else if (bucket.some((previous) => equals(previous, reason))) continue; + else bucket.push(reason); + out.push(reason); + } + return out; +}; +/** @internal */ +const causeCombine = /*#__PURE__*/ dual(2, (self, that) => { + if (self.reasons.length === 0) return that; + else if (that.reasons.length === 0) return self; + const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons)); + return equals(self, newCause) ? self : newCause; +}); +/** +* Appends the interrupts from `interrupts` that `self` does not contain yet. +* Unlike `causeCombine`, it never calls hash or equality methods, which can be +* user-defined, random, or throwing. +* +* @internal +*/ +const causeAddInterrupts = (self, interrupts) => { + const reasons = self.reasons.slice(); + for (const reason of interrupts.reasons) if (isInterruptReason(reason) && !reasons.some((r) => isInterruptReason(r) && r.fiberId === reason.fiberId && r.annotations === reason.annotations)) reasons.push(reason); + return reasons.length === self.reasons.length ? self : new CauseImpl(reasons); +}; +/** @internal */ +var Die = class extends ReasonBase { + constructor(defect, annotations = constEmptyAnnotations) { + super("Die", annotations, defect); + this.defect = defect; + } + toString() { + return `Die(${format(this.defect)})`; + } + toJSON() { + return { + _tag: "Die", + defect: this.defect + }; + } + [symbol](that) { + return isDieReason(that) && equals(this.defect, that.defect) && equals(this.annotations, that.annotations); + } + [symbol$1]() { + return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations))); + } +}; +/** @internal */ +const causeDie = (defect) => new CauseImpl([new Die(defect)]); +/** @internal */ +const causeAnnotate = /*#__PURE__*/ dual((args) => isCause(args[0]), (self, annotations, options) => { + if (annotations.mapUnsafe.size === 0) return self; + return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options))); +}); +/** @internal */ +const isFailReason = (self) => self._tag === "Fail"; +/** @internal */ +const isDieReason = (self) => self._tag === "Die"; +/** @internal */ +const isInterruptReason = (self) => self._tag === "Interrupt"; +function defaultEvaluate(_fiber) { + return exitDie(`Effect.evaluate: Not implemented`); +} +/** @internal */ +const makePrimitiveProto = (options) => ({ + ...EffectProto, + [identifier]: options.op, + [evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate, + [contA]: options[contA], + [contE]: options[contE], + [contAll]: options[contAll] +}); +/** @internal */ +const makePrimitive = (options) => { + const Proto = makePrimitiveProto(options); + const PrimitiveImpl = function(value) { + this[args] = value; + }; + PrimitiveImpl.prototype = Proto; + return function(value) { + return new PrimitiveImpl(value); + }; +}; +/** @internal */ +const makeExit = (options) => { + const Proto = { + [ExitTypeId]: ExitTypeId, + _tag: options.op, + get [options.prop]() { + return this[args]; + }, + ...makePrimitiveProto(options), + toString() { + return `${options.op}(${format(this[args])})`; + }, + toJSON() { + return { + _id: "Exit", + _tag: options.op, + [options.prop]: this[args] + }; + }, + [symbol](that) { + return isExit(that) && that._tag === this._tag && equals(this["~effect/Effect/args"], that["~effect/Effect/args"]); + }, + [symbol$1]() { + return combine(string(options.op), hash(this[args])); + } + }; + const ExitPrimitive = function(value) { + this[args] = value; + }; + ExitPrimitive.prototype = Proto; + return function(value) { + return new ExitPrimitive(value); + }; +}; +/** @internal */ +const exitSucceed = /*#__PURE__*/ makeExit({ + op: "Success", + prop: "value", + [evaluate](fiber) { + const cont = fiber.getCont(contA); + return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this); + } +}); +/** @internal */ +const StackTraceKey = { key: "effect/Cause/StackTrace" }; +/** @internal */ +const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" }; +/** @internal */ +const exitFailCause = /*#__PURE__*/ makeExit({ + op: "Failure", + prop: "cause", + [evaluate](fiber) { + let cause = this[args]; + let annotated = false; + if (fiber.cache.stackFrame) { + cause = causeAnnotate(cause, { mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]) }); + annotated = true; + } + let cont = fiber.getCont(contE); + const interruptedCause = fiber._interruptedCause; + if (interruptedCause && fiber.interruptible) { + let skippedHandler = false; + while (cont && fiber.interruptible) { + skippedHandler ||= identifier in cont; + cont = fiber.getCont(contE); + } + if (skippedHandler) cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail")); + cause = causeAddInterrupts(cause, interruptedCause); + annotated = true; + } + return cont ? cont[contE](cause, fiber, annotated ? void 0 : this) : fiber.yieldWith(annotated ? exitFailCause(cause) : this); + } +}); +/** @internal */ +const exitDie = (defect) => exitFailCause(causeDie(defect)); +/** @internal */ +const withFiber = /*#__PURE__*/ makePrimitive({ + op: "WithFiber", + [evaluate](fiber) { + return this[args](fiber); + } +}); +/** @internal */ +const DoneTypeId = "~effect/Cause/Done"; +/** @internal */ +const isDone = (u) => hasProperty(u, DoneTypeId); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effectable.js +/** +* Create a low-level `Effect` prototype. +* +* **When to use** +* +* Use when you need to create a custom Effect-like value without extending a +* class, by providing a label and an evaluate function that receives the +* current fiber. +* +* **Details** +* +* When the effect is evaluated, it calls `evaluate` with the current fiber. +* +* @see {@link Class} for a class-based approach to defining custom Effect values +* @see {@link Mixin} for wrapping an existing class constructor +* +* @stability stable +* @category prototypes +* @since 4.0.0 +*/ +const Prototype = (options) => makePrimitiveProto({ + op: options.label, + [evaluate]: options.evaluate +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Context.js +/** +* Runtime type identifier attached to `Context` service keys and used by +* `isKey` to recognize them. +* +* @stability stable +* @category type IDs +* @since 4.0.0 +*/ +const ServiceTypeId = "~effect/Context/Service"; +/** +* Creates a `Context` service key. +* +* **When to use** +* +* Use when you need to define a context service key for a dependency that must +* be provided by the surrounding context. +* +* **Details** +* +* Call `Context.Service("Key")` for a function-style key, or use the two-stage +* form `Context.Service()("Key")` for class-style service +* declarations. The returned key can be yielded as an Effect and passed to +* `Context.make`, `Context.add`, and the Context getter functions. +* +* **Gotchas** +* +* The string key is the runtime identity of the service. Reusing the same key +* string for unrelated services makes them occupy the same slot in a +* `Context`. +* +* **Example** (Creating service keys) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a simple service +* const Database = Context.Service<{ +* query: (sql: string) => string +* }>("Database") +* +* // Create a service class +* class Config extends Context.Service()("Config") {} +* +* // Use the services to create contexts +* const db = Context.make(Database, { +* query: (sql) => `Result: ${sql}` +* }) +* const config = Context.make(Config, { port: 8080 }) +* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1" +* Context.get(config, Config).port // => 8080 +* ``` +* +* @see {@link Reference} for service keys with default values +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const Service = function() { + function KeyClass() {} + const self = KeyClass; + Object.setPrototypeOf(self, ServiceProto); + const init = (key, options) => { + self.key = key; + if (options?.defaultValue) { + self[ReferenceTypeId] = ReferenceTypeId; + self.defaultValue = options.defaultValue; + } + if (options?.make) self.make = options.make; + if (options?.fiberCached) cacheKeys.add(key); + return self; + }; + return arguments.length > 0 ? init(arguments[0], arguments[1]) : init; +}; +const ServiceProto = { + [ServiceTypeId]: ServiceTypeId, + .../*#__PURE__*/ Prototype({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)); + } + }), + toJSON() { + return { + _id: "Service", + key: this.key + }; + }, + of(self) { + return self; + }, + context(self) { + return make(this, self); + }, + use(f) { + return withFiber((fiber) => f(get(fiber.context, this))); + }, + useSync(f) { + return withFiber((fiber) => exitSucceed(f(get(fiber.context, this)))); + } +}; +const cacheKeys = /*#__PURE__*/ new Set(); +const ReferenceTypeId = "~effect/Context/Reference"; +const TypeId$2 = "~effect/Context"; +const FlattenAfterBaseHits = 8; +const makeImpl = (cacheRoot, base, overlay, depth, maxDepth) => { + const self = Object.create(Proto); + self.cacheRoot = cacheRoot ?? self; + self.base = base; + self.overlay = overlay; + self.depth = depth; + self._flat = void 0; + self.baseHits = 0; + self.maxDepth = maxDepth; + return self; +}; +const applyOverlays = (map, overlay) => { + if (!overlay) return; + applyOverlays(map, overlay.parent); + map.set(overlay.key, overlay.value); +}; +const flatten = (self) => { + if (self._flat) return self._flat; + if (!self.overlay) return self._flat = self.base; + const map = new Map(self.base); + applyOverlays(map, self.overlay); + return self._flat = map; +}; +const withFlat = (self, f) => { + const map = new Map(self.mapUnsafe); + f(map); + return makeImpl(void 0, map, void 0, 0, self.maxDepth); +}; +const notFound = /*#__PURE__*/ Symbol(); +const lookup = (self, key) => { + const impl = self; + for (let overlay = impl.overlay; overlay; overlay = overlay.parent) if (overlay.key === key) return overlay.value; + const value = impl.base.get(key); + if (value === void 0 && !impl.base.has(key)) return notFound; + if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) { + impl.base = flatten(impl); + impl.overlay = void 0; + impl.depth = 0; + } + return value; +}; +/** +* Creates a `Context` from an existing service map. +* +* **When to use** +* +* Use when constructing a low-level `Context` from a trusted map whose lifecycle +* you control. +* +* **Details** +* +* `options.maxDepth` sets how many `add` calls are kept as overlays before the +* context is rebased into a flat map (default `8`). Lower values make lookups +* cheaper, higher values make additions to a large base cheaper. Invalid +* values fall back to the default. +* +* Contexts derived with `add`, `pick`, `omit`, and `merge` keep the setting +* (`merge` from its first non-empty argument). `make`, `empty`, and `mergeAll` +* use the default. Layers are combined with `mergeAll`, so apply it to the +* final context rather than inside a layer. +* +* **Gotchas** +* +* Excessively large `maxDepth` values can cause stack overflow when overlays +* are materialized or rebased. Choose a modest value. +* +* The provided map is retained without copying and must not be mutated after +* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context +* construction. +* +* **Example** (Creating a context from a map) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a context from a Map (unsafe) +* const map = new Map([ +* ["Logger", { log: (_msg: string) => {} }] +* ]) +* +* const context = Context.makeUnsafe(map) +* context.mapUnsafe.size // => 1 +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe$2 = (mapUnsafe, options) => { + const maxDepth = options?.maxDepth; + return makeImpl(void 0, mapUnsafe, void 0, 0, Number.isInteger(maxDepth) && maxDepth >= 0 ? maxDepth : 8); +}; +const Proto = { + get mapUnsafe() { + return flatten(this); + }, + ...PipeInspectableProto, + [TypeId$2]: { _Services: (_) => _ }, + toJSON() { + return { + _id: "Context", + services: Array.from(this.mapUnsafe).map(([key, value]) => ({ + key, + value + })) + }; + }, + [symbol](that) { + if (!isContext(that)) return false; + const self = this.mapUnsafe; + const other = that.mapUnsafe; + if (self.size !== other.size) return false; + for (const [key, value] of self) if (!other.has(key) || !equals(value, other.get(key))) return false; + return true; + }, + [symbol$1]() { + return number(this.mapUnsafe.size); + } +}; +/** @internal */ +const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot; +/** +* Checks whether the provided argument is a `Context`. +* +* **When to use** +* +* Use to narrow an unknown value before passing it to APIs that require a +* `Context`. +* +* **Details** +* +* This checks the runtime `Context` marker and does not inspect which services +* the context contains. +* +* **Gotchas** +* +* This guard only proves that the value is a `Context`; it does not prove that +* any specific service is present. +* +* **Example** (Checking for contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.isContext(Context.empty()) // => true +* ``` +* +* @see {@link isKey} for checking service keys +* @see {@link isReference} for checking references with defaults +* +* @stability stable +* @category guards +* @since 2.0.0 +*/ +const isContext = (u) => hasProperty(u, TypeId$2); +/** +* Checks whether the provided argument is a `Reference`. +* +* **Example** (Checking for references) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (_msg: string) => {} }) +* }) +* +* Context.isReference(LoggerRef) // => true +* Context.isReference(Context.Service("Key")) // => false +* ``` +* +* @stability stable +* @category guards +* @since 3.11.0 +*/ +const isReference = (u) => !!u[ReferenceTypeId]; +/** +* Returns an empty `Context`. +* +* **Example** (Creating an empty context) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* Context.empty().mapUnsafe.size // => 0 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty$1 = () => emptyContext; +const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map()); +/** +* Creates a new `Context` with a single service associated to the key. +* +* **Example** (Creating a context with one service) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* +* const context = Context.make(Port, { PORT: 8080 }) +* +* Context.get(context, Port).PORT // => 8080 +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const make = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]])); +/** +* Adds a service to a given `Context`. +* +* **When to use** +* +* Use when you need to store a known service value in a `Context`. +* +* **Details** +* +* If the context already contains the same service key, the new service +* replaces the previous one. +* +* **Example** (Adding a service to a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const someContext = Context.make(Port, { PORT: 8080 }) +* +* const context = pipe( +* someContext, +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link addOrOmit} for adding or removing a service from an `Option` +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service)); +/** +* Adds a service by key to a given `Context` using a string key. +* +* @stability stable +* @category combining +* @since 4.0.0 +*/ +const addUnsafe = (self, key, service) => { + const impl = self; + const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot; + if (impl.depth >= impl.maxDepth) { + const map = new Map(impl._flat ?? impl.base); + if (!impl._flat) applyOverlays(map, impl.overlay); + map.set(key, service); + return makeImpl(cacheRoot, map, void 0, 0, impl.maxDepth); + } + return makeImpl(cacheRoot, impl.base, { + key, + value: service, + parent: impl.overlay + }, impl.depth + 1, impl.maxDepth); +}; +/** +* Returns the service currently stored for a key, or `undefined` when the key +* is absent. +* +* **When to use** +* +* Use when you need to read the service stored for a key without resolving +* `Context.Reference` defaults. +* +* **Gotchas** +* +* This is a raw lookup and does not resolve default values for +* `Context.Reference` keys. +* +* @see {@link getOption} for a reference-aware optional lookup +* +* @stability stable +* @category getters +* @since 4.0.0 +*/ +const getOrUndefined = /*#__PURE__*/ dual(2, (self, key) => getOrUndefinedUnsafe(self, key.key)); +/** @internal */ +const getOrUndefinedUnsafe = (self, key) => { + const value = lookup(self, key); + return value === notFound ? void 0 : value; +}; +/** +* Gets a service from the context that corresponds to the given key. +* +* **When to use** +* +* Use when you need type-checked access to a service already included in the +* context type. +* +* **Example** (Getting a service from a context) +* +* ```ts import.meta.vitest +* import { Context, pipe } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const context = pipe( +* Context.make(Port, { PORT: 8080 }), +* Context.add(Timeout, { TIMEOUT: 5000 }) +* ) +* +* Context.get(context, Timeout).TIMEOUT // => 5000 +* ``` +* +* @see {@link getOption} for optional service access +* @see {@link getOrElse} for fallback values +* +* @stability stable +* @category getters +* @since 2.0.0 +*/ +const get = /* @__PURE__ */ dual(2, (self, service) => { + const value = lookup(self, service.key); + if (value === notFound) { + if (isReference(service)) return getDefaultValue(service); + throw serviceNotFoundError(service); + } + return value; +}); +const defaultValueCacheKey = "~effect/Context/defaultValue"; +const getDefaultValue = (ref) => { + if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey]; + return ref[defaultValueCacheKey] = ref.defaultValue(); +}; +const serviceNotFoundError = (service) => { + const error = /* @__PURE__ */ new Error(`Service not found${service.key ? `: ${String(service.key)}` : ""}`); + if (error.stack) { + const lines = error.stack.split("\n"); + lines.splice(1, 3); + error.stack = lines.join("\n"); + } + return error; +}; +/** +* Merges two `Context`s into one. +* +* **When to use** +* +* Use when you need to combine two contexts. +* +* **Details** +* +* When both contexts contain the same service key, the service from `that` +* overrides the service from `self`. +* +* **Example** (Merging two contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* +* const context = Context.merge(firstContext, secondContext) +* +* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT] +* values // => [8080, 5000] +* ``` +* +* @see {@link mergeAll} for merging more than two contexts at once +* +* @stability stable +* @category combining +* @since 2.0.0 +*/ +const merge = /*#__PURE__*/ dual(2, (self, that) => { + if (self.mapUnsafe.size === 0) return that; + if (that.mapUnsafe.size === 0) return self; + return withFlat(self, (map) => that.mapUnsafe.forEach((value, key) => map.set(key, value))); +}); +/** +* Merges any number of `Context`s into one. +* +* **When to use** +* +* Use when you need to combine a variadic list of contexts. +* +* **Details** +* +* When multiple contexts contain the same service key, the service from the +* last context with that key is kept. +* +* **Example** (Merging multiple contexts) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* const Port = Context.Service<{ PORT: number }>("Port") +* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout") +* const Host = Context.Service<{ HOST: string }>("Host") +* +* const firstContext = Context.make(Port, { PORT: 8080 }) +* const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) +* const thirdContext = Context.make(Host, { HOST: "localhost" }) +* +* const context = Context.mergeAll( +* firstContext, +* secondContext, +* thirdContext +* ) +* +* context.mapUnsafe.size // => 3 +* ``` +* +* @see {@link merge} for merging two contexts +* +* @stability stable +* @category combining +* @since 3.12.0 +*/ +const mergeAll$1 = (...ctxs) => { + const map = /* @__PURE__ */ new Map(); + for (let i = 0; i < ctxs.length; i++) ctxs[i].mapUnsafe.forEach((value, key) => { + map.set(key, value); + }); + return makeUnsafe$2(map); +}; +/** +* Creates a context key with a default value. +* +* **When to use** +* +* Use when you need to define a context key with a lazily computed default +* value. +* +* **Details** +* +* `Context.Reference` allows you to create a key that can hold a value. You +* can provide a default value for the service, which will automatically be used +* when the context is accessed, or override it with a custom implementation +* when needed. The default value is computed lazily and cached on the +* reference. +* +* **Example** (Creating references with default values) +* +* ```ts import.meta.vitest +* import { Context } from "effect" +* +* // Create a reference with a default value +* const messages: Array = [] +* const LoggerRef = Context.Reference("Logger", { +* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) }) +* }) +* +* // The reference provides the default value when accessed from an empty context +* const context = Context.empty() +* const logger = Context.get(context, LoggerRef) +* +* // You can also override the default value +* const customContext = Context.make(LoggerRef, { +* log: (msg: string) => messages.push(`Custom: ${msg}`) +* }) +* const customLogger = Context.get(customContext, LoggerRef) +* logger.log("default") +* customLogger.log("message") +* messages // => ["Default: default", "Custom: message"] +* ``` +* +* @see {@link Service} for required services without default values +* +* @stability stable +* @category services +* @since 3.11.0 +*/ +const Reference = Service; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Array.js +/** +* Exposes the global array constructor. +* +* **When to use** +* +* Use to access native JavaScript array constructor methods such as `isArray` +* or `from` from the Effect module namespace. +* +* **Example** (Accessing the Array constructor) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.Array === globalThis.Array // => true +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const Array$1 = globalThis.Array; +/** +* Converts an `Iterable` to an `Array`. +* +* **When to use** +* +* Use to convert any `Iterable` (Set, Generator, etc.) into an array. +* +* **Details** +* +* If the input is already an array, this returns it by reference without +* copying. Otherwise, it creates a new array from the iterable. Use `copy` if +* you need a fresh array even when the input is already an array. +* +* **Example** (Converting a Set to an array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.fromIterable(new Set([1, 2, 3])) // => [1, 2, 3] +* ``` +* +* @see {@link ensure} — wrap a single value or return an existing array +* @see {@link copy} — create a shallow copy of an array +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const fromIterable = (collection) => Array$1.isArray(collection) ? collection : Array$1.from(collection); +Array$1.isArray; +/** +* Creates an empty array. +* +* **When to use** +* +* Use to create a typed empty array without allocating placeholder elements. +* +* **Example** (Creating an empty array) +* +* ```ts import.meta.vitest +* import { Array } from "effect" +* +* Array.empty() // => [] +* ``` +* +* @see {@link of} — create a single-element array +* @see {@link make} — create from multiple values +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const empty = () => []; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scheduler.js +/** +* Controls how runnable Effect fiber tasks are dispatched. +* +* A scheduler decides how tasks are queued, when queued tasks run, and when a +* fiber should pause so other work can continue. This module includes the +* scheduler service reference, the default `MixedScheduler`, dispatcher types +* for queued tasks, and references for tuning or disabling automatic scheduler +* yields. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Context reference for the scheduler used by the Effect runtime. +* +* **When to use** +* +* Use when you need to replace scheduling behavior globally in tests or runtime +* setup, such as forcing deterministic task dispatch. +* +* **Details** +* +* The default value creates a `MixedScheduler`. Provide this service to +* customize execution mode, task dispatching, or yield behavior. +* +* @stability stable +* @category services +* @since 2.0.0 +*/ +const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", { + fiberCached: true, + defaultValue: () => new MixedScheduler() +}); +const setMicrotask = (f) => { + let cancelled = false; + Promise.resolve().then(() => { + if (!cancelled) f(); + }); + return () => { + cancelled = true; + }; +}; +const setTimer = "setImmediate" in globalThis ? (f) => { + const timer = globalThis.setImmediate(f); + return () => globalThis.clearImmediate(timer); +} : (f) => { + const timer = setTimeout(f, 0); + return () => clearTimeout(timer); +}; +const setImmediate = (f) => { + try { + return setTimer(f); + } catch { + return setMicrotask(f); + } +}; +var PriorityBuckets = class { + buckets = []; + scheduleTask(task, priority) { + const buckets = this.buckets; + const len = buckets.length; + let bucket; + let index = 0; + for (; index < len; index++) { + if (buckets[index][0] > priority) break; + bucket = buckets[index]; + } + if (bucket && bucket[0] === priority) bucket[1].push(task); + else if (index === len) buckets.push([priority, [task]]); + else buckets.splice(index, 0, [priority, [task]]); + } + drain() { + const buckets = this.buckets; + this.buckets = []; + return buckets; + } +}; +/** +* Provides a scheduler implementation that batches queued tasks and dispatches them by +* priority. +* +* **When to use** +* +* Use when you need the default runtime scheduler directly, including a +* scheduler that batches queued work by priority and preserves FIFO order within +* each priority. +* +* **Details** +* +* `MixedScheduler` supports synchronous and asynchronous execution modes, uses +* operation counts to decide when fibers should yield, and is the default +* scheduler implementation. +* +* **Gotchas** +* +* On Cloudflare Workers, request-owned scheduler timers can be discarded, +* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the +* whole application; see `HttpRouter.toWebHandler` for a recipe. +* Sync mode does not yield to the event loop: CPU-heavy work delays other +* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix +* request-owned timers (such as `Effect.sleep`) or request-bound async contexts. +* +* @stability stable +* @category models +* @since 2.0.0 +*/ +var MixedScheduler = class { + executionMode; + setImmediate; + constructor(executionMode = "async", setImmediateFn) { + this.executionMode = executionMode; + this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate); + } + /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * + * @since 2.0.0 + */ + shouldYield(fiber) { + return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield; + } + /** + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 + */ + makeDispatcher() { + return new MixedSchedulerDispatcher(this.setImmediate); + } +}; +var MixedSchedulerDispatcher = class { + tasks = /*#__PURE__*/ new PriorityBuckets(); + running = void 0; + setImmediate; + constructor(setImmediateFn = setImmediate) { + this.setImmediate = setImmediateFn; + } + /** + * @since 2.0.0 + */ + scheduleTask(task, priority) { + this.tasks.scheduleTask(task, priority); + if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled); + } + /** + * @since 2.0.0 + */ + afterScheduled = () => { + this.running = void 0; + this.runTasks(); + }; + /** + * @since 2.0.0 + */ + runTasks() { + const buckets = this.tasks.drain(); + for (let i = 0; i < buckets.length; i++) { + const toRun = buckets[i][1]; + for (let j = 0; j < toRun.length; j++) toRun[j](); + } + } + /** + * @since 2.0.0 + */ + flush() { + while (this.tasks.buckets.length > 0) { + if (this.running !== void 0) { + this.running(); + this.running = void 0; + } + this.runTasks(); + } + } +}; +/** +* Context reference that controls the maximum number of operations a fiber +* can perform before yielding control back to the scheduler. +* +* **When to use** +* +* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler +* operation budget that triggers a yield. +* +* **Details** +* +* The default value is `2048` operations, which balances performance and +* fairness by helping prevent long-running fibers from monopolizing the +* execution thread. +* +* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", { + fiberCached: true, + defaultValue: () => 2048 +}); +/** +* Context reference that controls whether the runtime should bypass scheduler +* yield checks. When set to `true`, the fiber run loop won't call +* `Scheduler.shouldYield`. +* +* **When to use** +* +* Use to bypass scheduler yield checks for controlled runtime workloads where +* cooperative yielding should be disabled. +* +* **Gotchas** +* +* Setting this reference to `true` can let long-running fibers monopolize the +* JavaScript thread. +* +* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks +* @see {@link Scheduler} for providing custom scheduler yield behavior +* +* @stability stable +* @category services +* @since 4.0.0 +*/ +const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", { + fiberCached: true, + defaultValue: () => false +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Tracer.js +/** +* Defines the string key for the parent-span context service. +* +* **When to use** +* +* Use when you need the raw context key for parent span lookup in lower-level +* tracing code. +* +* **Example** (Reading the parent span key) +* +* ```ts import.meta.vitest +* import { Tracer } from "effect" +* +* // The key used to identify parent spans in the context +* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan" +* ``` +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const ParentSpanKey = "effect/Tracer/ParentSpan"; +/** +* Defines the string key for the active tracer context reference. +* +* **When to use** +* +* Use when you need the raw context key for active tracer lookup in lower-level +* tracing code. +* +* @stability stable +* @category constants +* @since 4.0.0 +*/ +const TracerKey = "effect/Tracer"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/metric.js +/** @internal */ +const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics"; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/references.js +/** @internal */ +const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", { + fiberCached: true, + defaultValue: constUndefined +}); +/** @internal */ +const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", { + fiberCached: true, + defaultValue: constTrue +}); +/** @internal */ +const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +/** @internal */ +const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", { + fiberCached: true, + defaultValue: () => "Info" +}); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/effect.js +/** @internal */ +var Interrupt = class extends ReasonBase { + constructor(fiberId, annotations = constEmptyAnnotations) { + super("Interrupt", annotations, "Interrupted"); + this.fiberId = fiberId; + } + toString() { + return `Interrupt(${this.fiberId})`; + } + toJSON() { + return { + _tag: "Interrupt", + fiberId: this.fiberId + }; + } + [symbol](that) { + return isInterruptReason(that) && this.fiberId === that.fiberId && this.annotations === that.annotations; + } + [symbol$1]() { + return string(`${this._tag}:${this.fiberId}`); + } +}; +/** @internal */ +const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]); +/** @internal */ +const hasFails = (self) => self.reasons.some(isFailReason); +/** @internal */ +const hasDies = (self) => self.reasons.some(isDieReason); +/** +* Defects take precedence over typed failures when causes are combined: if +* the cause contains a `Die`, every `Fail` becomes a `Die`. `Done` signals +* stay typed so pulls still complete. +* +* @internal +*/ +const causeElectDefects = (self) => hasDies(self) && hasFails(self) ? causeFromReasons(self.reasons.map((reason) => reason._tag === "Fail" && !isDone(reason.error) ? new Die(reason.error, reason.annotations) : reason)) : self; +/** @internal */ +const hasInterrupts = (self) => self.reasons.some(isInterruptReason); +/** @internal */ +const causeSquash = (self) => { + let die; + for (const reason of self.reasons) { + if (reason._tag === "Fail") return reason.error; + if (reason._tag === "Die") die ??= reason; + } + if (die !== void 0) return die.defect; + if (self.reasons.length > 0) return new globalThis.Error("All fibers interrupted without error"); + return new globalThis.Error("Empty cause"); +}; +/** @internal */ +const FiberTypeId = "~effect/Fiber"; +const fiberVariance = { + _A: identity, + _E: identity +}; +const fiberIdStore = { id: 0 }; +const AsyncResource = /*#__PURE__*/ (() => { + try { + return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource; + } catch { + return; + } +})(); +const captureAsyncContext = () => AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber"); +/** @internal */ +const getCurrentFiber = () => globalThis[currentFiberTypeId]; +/** @internal */ +var FiberImpl = class { + constructor(context, interruptible = true) { + this.setContext(context); + this.id = ++fiberIdStore.id; + this.currentOpCount = 0; + this.interruptible = interruptible; + this._stack = []; + this._observers = void 0; + this._exit = void 0; + this._children = void 0; + this._interruptedCause = void 0; + this._yielded = void 0; + this._running = false; + this._deferredInterrupt = false; + this._parent = void 0; + this._asyncContext = void 0; + this.cache.runtimeMetrics?.recordFiberStart(this.context); + } + get [FiberTypeId]() { + return fiberVariance; + } + get currentDispatcher() { + return this._dispatcher ??= this.cache.scheduler.makeDispatcher(); + } + getRef(ref) { + return get(this.context, ref); + } + addObserver(cb) { + if (this._exit) { + cb(this._exit); + return constVoid; + } + if (this._observers === void 0) this._observers = [cb]; + else this._observers.push(cb); + return () => this.removeObserver(cb); + } + removeObserver(cb) { + if (this._exit || this._observers === void 0) return; + const index = this._observers.indexOf(cb); + if (index >= 0) this._observers.splice(index, 1); + } + interruptUnsafe(fiberId, annotations) { + if (this._exit) return; + let cause = causeInterrupt(fiberId); + if (this.cache.stackFrame) cause = causeAnnotate(cause, make(StackTraceKey, this.cache.stackFrame)); + if (annotations) cause = causeAnnotate(cause, annotations); + this._interruptedCause = this._interruptedCause ? causeAddInterrupts(this._interruptedCause, cause) : cause; + if (this.interruptible) { + if (this._running) this._deferredInterrupt = true; + else this.evaluate(failCause(this._interruptedCause)); + } + } + pollUnsafe() { + return this._exit; + } + evaluate(effect) { + if (this._exit) return; + else if (this._asyncContext !== void 0) { + const asyncContext = this._asyncContext; + this._asyncContext = void 0; + try { + return asyncContext.runInAsyncScope(this.evaluate, this, effect); + } finally { + asyncContext.emitDestroy(); + } + } else if (this._yielded !== void 0) { + const yielded = this._yielded; + this._yielded = void 0; + yielded(); + } + const exit = this.runLoop(effect); + if (exit === Yield) { + this._asyncContext = captureAsyncContext(); + return; + } + const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this); + if (interruptChildren !== void 0) return this.evaluate(flatMap(interruptChildren, () => exit)); + this._exit = exit; + this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit); + if (this._parent) { + this._parent._children?.delete(this); + this._parent = void 0; + } + if (this._observers !== void 0) { + const observers = this._observers; + this._observers = void 0; + for (let i = 0; i < observers.length; i++) observers[i](exit); + } + this._stack.length = 0; + this._children = void 0; + this.context = empty$1(); + const cache = this.cache; + if (cache.span !== void 0 || cache.stackFrame !== void 0) this.cache = { + ...cache, + span: void 0, + stackFrame: void 0 + }; + } + runLoop(effect) { + const prevFiber = globalThis[currentFiberTypeId]; + globalThis[currentFiberTypeId] = this; + const prevRunning = this._running; + this._running = true; + let yielding = false; + let current = effect; + this.currentOpCount = 0; + try { + while (true) try { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + current = failCause(this._interruptedCause); + } + this.currentOpCount++; + const cache = this.cache; + if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) { + yielding = true; + const prev = current; + current = flatMap(yieldNow, () => prev); + } + current = cache.tracerContext ? cache.tracerContext(current, this) : current[evaluate](this); + if (current === Yield) { + const yielded = this._yielded; + if ("~effect/Exit" in yielded) { + this._deferredInterrupt = false; + this._yielded = void 0; + return yielded; + } else if (this._deferredInterrupt) { + this._yielded = void 0; + yielded(); + continue; + } + return Yield; + } + } catch (error) { + if (!hasProperty(current, "~effect/Effect/evaluate")) return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`); + current = exitDie(error); + } + } finally { + this._running = prevRunning; + globalThis[currentFiberTypeId] = prevFiber; + } + } + getCont(symbol) { + if (this._deferredInterrupt) { + this._deferredInterrupt = false; + return deferredInterruptCont; + } + while (true) { + const op = this._stack.pop(); + if (!op) return void 0; + const all = op[contAll]; + if (all !== void 0) { + const cont = all.call(op, this); + if (cont) { + cont[symbol] = cont; + return cont; + } + } + if (op[symbol]) return op; + } + } + succeedWith(value) { + if ((++this.currentOpCount & maxInlineSteps - 1) === 0) return exitSucceed(value); + const cont = this.getCont(contA); + return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value)); + } + yieldWith(value) { + this._yielded = value; + return Yield; + } + children() { + return this._children ??= /* @__PURE__ */ new Set(); + } + pipe() { + return pipeArguments(this, arguments); + } + setContext(context) { + const previous = this.context; + this.context = context; + if (previous !== void 0 && hasSameCache(previous, context)) return; + const root = context.cacheRoot; + const cache = root._fiberCache ??= makeFiberContextCache(context); + if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0; + this.cache = cache; + } + get currentSpanLocal() { + const span = this.cache.span; + return span?._tag === "Span" ? span : void 0; + } +}; +const makeFiberContextCache = (context) => { + const currentTracer = getOrUndefinedUnsafe(context, TracerKey); + return { + scheduler: get(context, Scheduler), + tracer: currentTracer, + tracerContext: currentTracer ? currentTracer["context"] : void 0, + tracerEnabled: get(context, TracerEnabled), + span: getOrUndefinedUnsafe(context, ParentSpanKey), + logLevel: get(context, CurrentLogLevel), + minimumLogLevel: get(context, MinimumLogLevel), + stackFrame: get(context, CurrentStackFrame), + runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey), + maxOpsBeforeYield: get(context, MaxOpsBeforeYield), + preventYield: get(context, PreventSchedulerYield) + }; +}; +const deferredInterruptCont = { + [contA](_value, fiber) { + return failCause(fiber._interruptedCause); + }, + [contE](_cause, fiber) { + return failCause(fiber._interruptedCause); + } +}; +const maxInlineSteps = 32; +const fiberMiddleware = { interruptChildren: void 0 }; +const fiberStackAnnotations = (fiber) => { + if (!fiber.cache.stackFrame) return void 0; + const annotations = /* @__PURE__ */ new Map(); + annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame); + return makeUnsafe$2(annotations); +}; +/** @internal */ +const fiberAwaitAll = (self) => callback((resume) => { + const iter = self[Symbol.iterator](); + const exits = []; + let cancel = void 0; + function loop() { + let result = iter.next(); + while (!result.done) { + if (result.value._exit) { + exits.push(result.value._exit); + result = iter.next(); + continue; + } + cancel = result.value.addObserver((exit) => { + exits.push(exit); + loop(); + }); + return; + } + resume(succeed(exits)); + } + loop(); + return sync(() => cancel?.()); +}); +/** @internal */ +const fiberInterruptAll = (fibers) => withFiber((parent) => { + const annotations = fiberStackAnnotations(parent); + let fiberArr = empty(); + for (const fiber of fibers) { + fiber.interruptUnsafe(parent.id, annotations); + fiberArr.push(fiber); + } + return asVoid(fiberAwaitAll(fiberArr)); +}); +/** @internal */ +const succeed = exitSucceed; +/** @internal */ +const failCause = exitFailCause; +/** @internal */ +const sync = /*#__PURE__*/ makePrimitive({ + op: "Sync", + [evaluate](fiber) { + const thunk = this[args]; + const value = thunk(); + const cont = fiber.getCont(contA); + return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value)); + } +}); +/** @internal */ +const suspend = /*#__PURE__*/ makePrimitive({ + op: "Suspend", + [evaluate](_fiber) { + const thunk = this[args]; + return thunk(); + } +}); +/** @internal */ +const yieldNow = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "Yield", + [evaluate](fiber) { + let resumed = false; + fiber.currentDispatcher.scheduleTask(() => { + if (resumed) return; + fiber.evaluate(exitVoid); + }, this["~effect/Effect/args"] ?? 0); + return fiber.yieldWith(() => { + resumed = true; + }); + } +}))(0); +/** @internal */ +const void_ = /*#__PURE__*/ succeed(void 0); +const callbackOptions = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Async", + [evaluate](fiber) { + let resumed = false; + let yielded = false; + const controller = this.withSignal ? new AbortController() : void 0; + const onCancel = this.register.call(fiber.cache.scheduler, (effect) => { + if (resumed) return; + resumed = true; + if (yielded) fiber.evaluate(effect); + else yielded = effect; + }, controller?.signal); + if (yielded !== false) return yielded; + yielded = true; + fiber.yieldWith(() => { + resumed = true; + }); + if (controller === void 0 && onCancel === void 0) return Yield; + fiber._stack.push(asyncFinalizer(() => { + resumed = true; + controller?.abort(); + return onCancel ?? exitVoid; + })); + return Yield; + } + }); + const AsyncImpl = function(register, withSignal) { + this.register = register; + this.withSignal = withSignal; + }; + AsyncImpl.prototype = Proto; + return function(register, withSignal) { + return new AsyncImpl(register, withSignal); + }; +}(); +const asyncFinalizer = /*#__PURE__*/ makePrimitive({ + op: "AsyncFinalizer", + [contAll](fiber) { + if (fiber.interruptible) { + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + } + }, + [contE](cause, _fiber) { + return hasInterrupts(cause) ? flatMap(combineFinalizerCause(exitFailCause(cause), this[args]()), () => failCause(cause)) : failCause(cause); + } +}); +/** @internal */ +const callback = (register) => callbackOptions(register, register.length >= 2); +/** @internal */ +const gen$1 = (...args) => { + if (args.length === 1) { + const body = args[0]; + return suspend(() => fromIteratorUnsafe(body())); + } + const [options, body] = args; + return suspend(() => fromIteratorUnsafe(body.call(options.self))); +}; +const fnBody = (bodyOrOptions, pipeables) => typeof bodyOrOptions === "function" ? bodyOrOptions : pipeables.shift().bind(bodyOrOptions.self); +/** @internal */ +const fnUntraced = (bodyOrOptions, ...pipeables) => { + const body = fnBody(bodyOrOptions, pipeables); + const fn = pipeables.length === 0 ? function() { + return suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + } : function() { + let effect = suspend(() => fromIteratorUnsafe(body.apply(this, arguments))); + for (let i = 0; i < pipeables.length; i++) effect = pipeables[i](effect, ...arguments); + return effect; + }; + return defineFunctionLength(body.length, fn); +}; +const defineFunctionLength = (length, fn) => Object.defineProperty(fn, "length", { + value: length, + configurable: true +}); +const fromIteratorUnsafe = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "Iterator", + [contA](value, fiber) { + const iter = this.iterator; + while (true) { + const state = iter.next(value); + if (state.done) return succeed(state.value); + if (!effectIsExit(state.value)) { + fiber._stack.push(this); + return state.value; + } else if (state.value._tag === "Failure") return state.value; + value = state.value.value; + } + }, + [evaluate](fiber) { + return this[contA](this.initial, fiber); + } + }); + const IteratorImpl = function(iterator, initial) { + this.iterator = iterator; + this.initial = initial; + }; + IteratorImpl.prototype = Proto; + return function(iterator, initial) { + return new IteratorImpl(iterator, initial); + }; +}(); +/** @internal */ +const as = /*#__PURE__*/ dual(2, (self, value) => new ContImpl(self, returnPayload, succeed(value))); +const evaluateCont = function(fiber) { + fiber._stack.push(this); + return this[args]; +}; +const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccess", + [evaluate]: evaluateCont +}); +const ContImpl = function(self, cont, payload) { + this[args] = self; + this[contA] = cont; + this.payload = payload; +}; +ContImpl.prototype = OnSuccessProto; +const returnPayload = function() { + return this.payload; +}; +const continuationMarksStack = /*#__PURE__*/ (() => { + const limit = /*#__PURE__*/ getStackTraceLimit(); + if (limit === 0) return false; + const marker = "~effect/Effect/stackProbe"; + const probe = { [marker]: function stackProbe() { + return /* @__PURE__ */ new Error(); + } }; + setStackTraceLimit(1); + const error = /*#__PURE__*/ probe[marker](); + setStackTraceLimit(limit); + return error.stack?.includes("[as " + marker + "]") === true; +})(); +const mapCont = function(value, fiber) { + const f = this.payload; + return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value))); +}; +const andThenCont = function(value) { + const f = this.payload; + return f(value); +}; +/** @internal */ +const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid); +/** @internal */ +const flatMap = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f)); +/** @internal */ +const effectIsExit = (effect) => effect[ExitTypeId] !== void 0; +/** @internal */ +const map = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f)); +/** @internal */ +const exitIsSuccess = (self) => self._tag === "Success"; +/** @internal */ +const exitVoid = /*#__PURE__*/ exitSucceed(void 0); +/** @internal */ +const exitAsVoidAll = (exits) => { + const failures = []; + for (const exit of exits) if (exit._tag === "Failure") failures.push(...exit.cause.reasons); + return failures.length === 0 ? exitVoid : exitFailCause(causeFromReasons(failures)); +}; +/** @internal */ +const updateContext = /*#__PURE__*/ dual(2, (self, f) => withFiber((fiber) => { + const prevContext = fiber.context; + const nextContext = f(prevContext); + if (prevContext === nextContext) return self; + fiber.setContext(nextContext); + onExitUnsafe(fiber, () => { + fiber.setContext(prevContext); + }); + return self; +})); +/** @internal */ +const provideContext = /*#__PURE__*/ dual(2, (self, context) => { + if (effectIsExit(self)) return self; + return updateContext(self, merge(context)); +}); +/** @internal */ +const provideService = function() { + if (arguments.length === 1) return dual(2, (self, impl) => provideServiceImpl(self, arguments[0], impl)); + return dual(3, (self, service, impl) => provideServiceImpl(self, service, impl)).apply(this, arguments); +}; +const provideServiceImpl = (self, service, implementation) => updateContext(self, add(service, implementation)); +/** @internal */ +const catchCause = /*#__PURE__*/ dual(2, (self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f)); +const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnFailure", + [evaluate]: evaluateCont +}); +const OnFailureImpl = function(self, f) { + this[args] = self; + this[contE] = f; +}; +OnFailureImpl.prototype = OnFailureProto; +const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnSuccessAndFailure", + [evaluate]: evaluateCont +}); +const OnSuccessAndFailureImpl = function(self, onSuccess, onFailure) { + this[args] = self; + this[contA] = onSuccess; + this[contE] = onFailure; +}; +OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto; +/** @internal */ +const exit = (self) => effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self); +const exitPrimitive = /*#__PURE__*/ makePrimitive({ + op: "Exit", + [evaluate](fiber) { + fiber._stack.push(this); + return this[args]; + }, + [contA](value, fiber, exit) { + return fiber.succeedWith(exit ?? exitSucceed(value)); + }, + [contE](cause, fiber, exit) { + return fiber.succeedWith(exit ?? exitFailCause(cause)); + } +}); +/** @internal */ +const ScopeTypeId = "~effect/Scope"; +/** @internal */ +const ScopeCloseableTypeId = "~effect/Scope/Closeable"; +/** @internal */ +const scopeTag = /*#__PURE__*/ Service("effect/Scope"); +/** @internal */ +const scopeClose = (self, exit_) => withFiber((fiber) => { + fiberEnterUninterruptibleUnsafe(fiber); + return scopeCloseUnsafe(self, exit_) ?? void_; +}); +/** @internal */ +const scopeCloseUnsafe = (self, exit_) => { + const state = self.state; + if (state._tag === "Closed") return; + self.state = { + _tag: "Closed", + exit: exit_ + }; + if (self.parent !== void 0) scopeRemoveFinalizerUnsafe(self.parent, self); + if (state._tag === "Empty") return; + if (state.finalizer !== void 0) return runFinalizer(state.finalizer, exit_); + const finalizers = state.finalizers; + if (finalizers.size === 1) return runFinalizer(finalizers.values().next().value, exit_); + return scopeCloseFinalizers(self, finalizers, exit_); +}; +const runFinalizer = (finalizer, exit_) => { + try { + return finalizer(exit_); + } catch (defect) { + return exitDie(defect); + } +}; +const combineFinalizerCause = (exit_, finalizer) => exitIsSuccess(exit_) ? finalizer : catchCause(finalizer, (cause) => failCause(causeElectDefects(causeCombine(exit_.cause, cause)))); +const scopeCloseFinalizers = /*#__PURE__*/ fnUntraced(function* (self, finalizers, exit_) { + let exits = []; + const fibers = []; + const arr = Array.from(finalizers); + const parent = getCurrentFiber(); + for (let i = arr.length - 1; i >= 0; i--) { + const [key, finalizer] = arr[i]; + if (self.strategy === "sequential") exits.push(yield* exit(runFinalizer(finalizer, exit_))); + else if (key !== parent) fibers.push(forkUnsafe$1(parent, runFinalizer(finalizer, exit_), true, true, "inherit")); + } + if (fibers.length > 0) exits = yield* fiberAwaitAll(fibers); + return yield* exitAsVoidAll(exits); +}); +/** @internal */ +const scopeForkUnsafe = (scope, finalizerStrategy) => { + const child = makeScope(finalizerStrategy, scope); + if (scope.state._tag === "Closed") { + child.state = scope.state; + return child; + } + scopeAddFinalizerUnsafe(scope, child, (exit) => scopeClose(child, exit)); + return child; +}; +/** @internal */ +const scopeAddFinalizerUnsafe = (scope, key, finalizer) => { + if (scope.state._tag === "Empty") scope.state = { + _tag: "Open", + finalizerKey: key, + finalizer, + finalizers: void 0 + }; + else if (scope.state._tag === "Open") { + const state = scope.state; + if (state.finalizer !== void 0) { + state.finalizers = /* @__PURE__ */ new Map([[state.finalizerKey, state.finalizer]]); + state.finalizerKey = void 0; + state.finalizer = void 0; + state.finalizers.set(key, finalizer); + } else state.finalizers.set(key, finalizer); + } +}; +/** @internal */ +const scopeRemoveFinalizerUnsafe = (scope, key) => { + if (scope.state._tag !== "Open") return; + const state = scope.state; + if (state.finalizerKey === key) scope.state = constScopeEmpty; + else if (state.finalizers !== void 0) { + state.finalizers.delete(key); + if (state.finalizers.size === 0) scope.state = constScopeEmpty; + } +}; +/** @internal */ +const scopeMakeUnsafe = (finalizerStrategy) => makeScope(finalizerStrategy, void 0); +const makeScope = (finalizerStrategy = "sequential", parent) => ({ + [ScopeCloseableTypeId]: ScopeCloseableTypeId, + [ScopeTypeId]: ScopeTypeId, + strategy: finalizerStrategy, + parent, + state: constScopeEmpty +}); +const constScopeEmpty = { _tag: "Empty" }; +/** @internal */ +const provideScope = /*#__PURE__*/ provideService(scopeTag); +/** @internal */ +const scopedWith = (f) => suspend(() => { + const scope = scopeMakeUnsafe(); + return onExit(f(scope), (exit) => suspend(() => scopeCloseUnsafe(scope, exit) ?? void_)); +}); +const OnExitImpl = /*#__PURE__*/ function() { + const Proto = /*#__PURE__*/ makePrimitiveProto({ + op: "OnExit", + [evaluate](fiber) { + fiber._stack.push(this); + return this.effect; + }, + [contAll](fiber) { + if (fiber.interruptible && this.interruptible !== true) { + fiber._stack.push(setInterruptibleTrue); + fiber.interruptible = false; + } + }, + [contA](value, _, exit) { + exit ??= exitSucceed(value); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(eff, (_) => exit) : exit; + }, + [contE](cause, _, exit) { + exit ??= exitFailCause(cause); + let eff; + try { + eff = this.onExit(exit); + } catch (defect) { + eff = exitDie(defect); + } + return eff ? flatMap(combineFinalizerCause(exit, eff), (_) => exit) : exit; + } + }); + const OnExitImpl = function(effect, onExit, interruptible) { + this.effect = effect; + this.onExit = onExit; + this.interruptible = interruptible; + }; + OnExitImpl.prototype = Proto; + return OnExitImpl; +}(); +/** @internal */ +const onExitPrimitive = (effect, onExit, interruptible) => new OnExitImpl(effect, onExit, interruptible); +/** +* Pushes an exit finalizer for the current `withFiber` evaluation. Only call inside `withFiber`. +* @internal +*/ +const onExitUnsafe = (fiber, f) => { + fiber._stack.push(new OnExitImpl(void 0, f, void 0)); +}; +/** @internal */ +const onExit = /*#__PURE__*/ dual(2, onExitPrimitive); +/** @internal */ +const uninterruptible = (self) => withFiber((fiber) => { + if (!fiber.interruptible) return self; + fiber.interruptible = false; + fiber._stack.push(setInterruptibleTrue); + return self; +}); +const setInterruptibleTrue = /*#__PURE__*/ (/* @__PURE__ */ makePrimitive({ + op: "SetInterruptible", + [contAll](fiber) { + fiber.interruptible = this[args]; + if (fiber._interruptedCause && fiber.interruptible) return () => failCause(fiber._interruptedCause); + } +}))(true); +/** +* Makes the current fiber uninterruptible for the returned effect without an +* extra primitive. Call only within `withFiber`. +* +* @internal +*/ +const fiberEnterUninterruptibleUnsafe = (fiber) => { + const impl = fiber; + if (!impl.interruptible) return; + impl.interruptible = false; + impl._stack.push(setInterruptibleTrue); +}; +/** @internal */ +const whileLoop = /*#__PURE__*/ makePrimitive({ + op: "While", + [contA](value, fiber) { + this[args].step(value); + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + }, + [evaluate](fiber) { + if (this["~effect/Effect/args"].while()) { + fiber._stack.push(this); + return this[args].body(); + } + return exitVoid; + } +}); +/** @internal */ +const forEach = /*#__PURE__*/ dual((args) => typeof args[1] === "function", (iterable, f, options) => suspend(() => { + const concurrency = resolveConcurrency(options?.concurrency); + if (concurrency === 1) return forEachSequential(iterable, f, options); + const items = fromIterable(iterable); + let length = items.length; + if (length === 0) return options?.discard ? void_ : succeed([]); + const out = options?.discard ? void 0 : new Array(length); + const eff = forEachConcurrent({ + f, + out + }, items, { concurrency }); + return eff ? as(eff, out) : succeed(out); +})); +const forEachSequential = (iterable, f, options) => suspend(() => { + const out = options?.discard ? void 0 : []; + const iterator = iterable[Symbol.iterator](); + let state = iterator.next(); + let index = 0; + return as(whileLoop({ + while: () => !state.done, + body: () => f(state.value, index++), + step: (b) => { + if (out) out.push(b); + state = iterator.next(); + } + }), out); +}); +/** @internal */ +const resolveConcurrency = (concurrency) => concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1); +const iterateConcurrentImpl = (options) => { + const onItem = options.onItem; + const step = options.step; + return (state, items, opts) => { + let index = 0; + const end = opts.end ?? items.length; + const concurrency = opts.concurrency; + let done = false; + let parentFiber; + let fibers; + let resume; + let terminal; + let effect; + const failDefect = (error) => { + const defect = exitDie(error); + terminal = defect; + done = true; + return fibers && fibers.size > 0 ? flatMap(uninterruptible(fiberInterruptAll(Array.from(fibers))), () => terminal ?? defect) : defect; + }; + const go = () => { + let paused = false; + for (; !terminal && index < end; index++) { + const item = items[index]; + const eff = effect ?? onItem(state, item, index); + if (effectIsExit(eff)) { + terminal = step(state, item, eff, index); + if (terminal) break; + } else if (!parentFiber) return callback((cb) => { + parentFiber = getCurrentFiber(); + fibers = /* @__PURE__ */ new Set(); + effect = eff; + resume = cb; + let result; + try { + result = go(); + } catch (error) { + return cb(failDefect(error)); + } + if (result) return cb(result); + return suspend(() => { + terminal ??= exitVoid; + return flatMap(fibers ? fiberInterruptAll(fibers) : void_, () => terminal?._tag === "Failure" ? terminal : void_); + }); + }); + else { + effect = void 0; + const fiber = forkUnsafe$1(parentFiber, eff, true, true, "inherit"); + if (fiber._exit) { + terminal = step(state, item, fiber._exit, index); + if (terminal) break; + continue; + } + fibers.add(fiber); + const currentIndex = index; + fiber.addObserver((exit) => { + fibers.delete(fiber); + try { + if (terminal) { + if (exit._tag === "Failure") { + const reasons = exit.cause.reasons.filter((reason) => reason._tag !== "Interrupt"); + if (reasons.length > 0) { + const cause = causeFromReasons(reasons); + terminal = exitFailCause(terminal._tag === "Failure" ? causeElectDefects(causeCombine(terminal.cause, cause)) : cause); + } + } + } else { + const result = step(state, item, exit, currentIndex); + if (result) { + terminal = result; + go(); + } + } + if (paused) { + const eff = go(); + if (eff) resume(eff); + } else if (done && fibers.size === 0) resume(terminal ?? void_); + } catch (error) { + resume(failDefect(error)); + } + }); + if (fibers.size < concurrency) continue; + paused = true; + index++; + return; + } + } + done = true; + if (terminal) { + if (fibers && fibers.size > 0) { + const annotations = fiberStackAnnotations(parentFiber); + fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations)); + return; + } + if (resume || terminal._tag === "Failure") return terminal; + } else if (resume) { + if (!fibers) return exitVoid; + else if (fibers.size === 0) resume(void_); + } + }; + return go(); + }; +}; +const forEachConcurrent = /*#__PURE__*/ iterateConcurrentImpl({ + onItem(state, item, index) { + return state.f(item, index); + }, + step(state, _, exit, index) { + if (exit._tag === "Failure") return exit; + else if (state.out) state.out[index] = exit.value; + } +}); +/** @internal */ +const forkUnsafe$1 = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => { + const parentRuntime = parent; + const interruptible = uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible; + const child = new FiberImpl(parentRuntime.context, interruptible); + if (!daemon) { + parentRuntime.children().add(child); + child._parent = parentRuntime; + } + if (immediate) child.evaluate(effect); + else { + child._asyncContext = captureAsyncContext(); + parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0); + } + return child; +}; +/** @internal */ +const runForkWith = (context) => (effect, options) => { + const fiber = new FiberImpl(options?.scheduler ? add(context, Scheduler, options.scheduler) : context, options?.uninterruptible !== true); + fiber.evaluate(effect); + if (fiber._exit) return fiber; + if (options?.signal) { + if (options.signal.aborted) fiber.interruptUnsafe(); + else { + const abort = () => fiber.interruptUnsafe(); + options.signal.addEventListener("abort", abort, { once: true }); + fiber.addObserver(() => options.signal.removeEventListener("abort", abort)); + } + } + if (options?.onFiberStart) options.onFiberStart(fiber); + return fiber; +}; +/** @internal */ +const runPromiseExitWith = (context) => { + const runFork = runForkWith(context); + return (effect, options) => { + const fiber = runFork(effect, options); + return new Promise((resolve) => { + fiber.addObserver((exit) => resolve(exit)); + }); + }; +}; +/** @internal */ +const runPromiseWith = (context) => { + const runPromiseExit = runPromiseExitWith(context); + return (effect, options) => runPromiseExit(effect, options).then((exit) => { + if (exit._tag === "Failure") throw causeSquash(exit.cause); + return exit.value; + }); +}; +/** @internal */ +const runPromise$1 = /*#__PURE__*/ runPromiseWith(/*#__PURE__*/ empty$1()); +const colors = { + bold: "1", + red: "31", + green: "32", + yellow: "33", + blue: "34", + cyan: "36", + white: "37", + gray: "90", + black: "30", + bgBrightRed: "101" +}; +colors.gray, colors.blue, colors.green, colors.yellow, colors.red, colors.bgBrightRed, colors.black; +const DeferredProto = { + ["~effect/Deferred"]: { + _A: identity, + _E: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const DeferredImpl = function() { + this.resumes = void 0; + this.effect = void 0; +}; +DeferredImpl.prototype = DeferredProto; +/** +* Creates an empty `Deferred` synchronously outside the `Effect` runtime. +* +* **When to use** +* +* Use to allocate a `Deferred` synchronously when direct allocation outside +* `Effect` is required. +* +* **Example** (Creating a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.isDoneUnsafe(deferred) // => false +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const makeUnsafe$1 = () => new DeferredImpl(); +const _await = (self) => callback((resume) => { + if (self.effect) return resume(self.effect); + self.resumes ??= []; + self.resumes.push(resume); + return sync(() => { + const resumes = self.resumes; + if (resumes === void 0) return; + const index = resumes.indexOf(resume); + if (index >= 0) resumes.splice(index, 1); + }); +}); +/** +* Attempts to complete the `Deferred` synchronously with the specified +* completion effect. +* +* **When to use** +* +* Use to complete a `Deferred` synchronously in low-level code that already has +* the completion effect. +* +* **Details** +* +* This mutates the `Deferred` directly and should be reserved for low-level +* code; prefer the effectful completion APIs when possible. Returns `true` if +* this call completed the `Deferred`, or `false` if it was already completed. +* +* **Example** (Completing a Deferred unsafely) +* +* ```ts import.meta.vitest +* import { Deferred, Effect } from "effect" +* +* const deferred = Deferred.makeUnsafe() +* Deferred.doneUnsafe(deferred, Effect.succeed(42)) // => true +* ``` +* +* @stability stable +* @category unsafe +* @since 4.0.0 +*/ +const doneUnsafe = (self, effect) => { + if (self.effect) return false; + self.effect = effect; + if (self.resumes) { + const resumes = self.resumes; + self.resumes = void 0; + for (let i = 0; i < resumes.length; i++) resumes[i](effect); + } + return true; +}; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Scope.js +/** +* Controls how long resources stay open. +* +* A scope is a lifetime boundary. Code can register cleanup effects on it, and +* closing the scope runs those cleanups with the `Exit` value that ended the +* work. Most application code uses higher-level APIs such as `Effect.scoped` +* and `Layer`, while this module is useful when code needs to create, provide, +* fork, close, or inspect scopes directly. +* +* @stability stable +* @since 2.0.0 +*/ +/** +* Creates a new `Scope` synchronously without wrapping it in an `Effect`. +* This is useful when you need a scope immediately but should be used with caution +* as it doesn't provide the same safety guarantees as the `Effect`-wrapped version. +* +* **When to use** +* +* Use when a scope must be allocated synchronously and the caller will close it +* manually. +* +* **Example** (Creating a scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const scope = Scope.makeUnsafe("sequential") +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* yield* Scope.addFinalizer(scope, Effect.sync(() => cleanups.push("Cleanup"))) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["Cleanup"] +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeUnsafe = scopeMakeUnsafe; +/** +* Provides a concrete `Scope` to an effect. +* +* **When to use** +* +* Use to run an effect that requires `Scope` with a scope managed by the +* caller. +* +* **Details** +* +* Providing the scope removes the `Scope` requirement from the effect context. +* +* **Example** (Providing a scope) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const program = Effect.gen(function*() { +* const scope = yield* Scope.Scope +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("cleanup"))) +* events.push("working") +* }) +* +* const withScope = Effect.gen(function*() { +* const scope = yield* Scope.make() +* yield* Scope.provide(scope)(program) +* yield* Scope.close(scope, Exit.void) +* }) +* +* Effect.runSync(withScope) +* events // => ["working", "cleanup"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const provide$2 = provideScope; +/** +* Creates a closeable child scope synchronously and registers it with a parent scope. +* +* **When to use** +* +* Use when a child scope must be created synchronously and the caller controls +* both parent and child scope lifetimes. +* +* **Details** +* +* Closing the parent closes the child with the same exit value, and closing the +* child detaches it from the parent. The optional finalizer strategy configures +* the child scope and defaults to `"sequential"` when omitted. +* +* **Example** (Creating a child scope synchronously) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const cleanups: Array = [] +* const program = Effect.gen(function*() { +* const parentScope = Scope.makeUnsafe("sequential") +* const childScope = Scope.forkUnsafe(parentScope, "parallel") +* yield* Scope.addFinalizer(parentScope, Effect.sync(() => cleanups.push("parent"))) +* yield* Scope.addFinalizer(childScope, Effect.sync(() => cleanups.push("child"))) +* yield* Scope.close(childScope, Exit.void) +* yield* Scope.close(parentScope, Exit.void) +* }) +* +* Effect.runSync(program) +* cleanups // => ["child", "parent"] +* ``` +* +* @stability stable +* @category combinators +* @since 4.0.0 +*/ +const forkUnsafe = scopeForkUnsafe; +/** +* Closes a scope and runs its registered finalizers. +* +* **When to use** +* +* Use to close a scope manually with a specific exit value. +* +* **Details** +* +* Finalizers run in the scope's configured order and receive the supplied +* `Exit`. +* By default, finalizers run uninterruptibly, so interrupting the closing fiber +* waits for them to finish; a finalizer can explicitly restore interruptibility. +* +* **Gotchas** +* +* Closing a scope that is already closed returns immediately, even when the +* finalizers of an earlier close are still running. +* +* **Example** (Running scope finalizers) +* +* ```ts import.meta.vitest +* import { Effect, Exit, Scope } from "effect" +* +* const events: Array = [] +* const resourceManagement = Effect.gen(function*() { +* const scope = yield* Scope.make("sequential") +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("database"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("file"))) +* yield* Scope.addFinalizer(scope, Effect.sync(() => events.push("memory"))) +* events.push("work") +* yield* Scope.close(scope, Exit.succeed("Success!")) +* }) +* +* Effect.runSync(resourceManagement) +* events // => ["work", "memory", "file", "database"] +* ``` +* +* @stability stable +* @category combinators +* @since 2.0.0 +*/ +const close = scopeClose; +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Layer.js +const TypeId = "~effect/Layer"; +const MemoMapTypeId = "~effect/Layer/MemoMap"; +const makeMemoMapEntry = (memoMap, layer) => { + const entry = { + observers: 0, + deferred: makeUnsafe$1(), + scope: makeUnsafe(), + finalizer: (exit) => suspend(() => { + if (--entry.observers > 0) return void_; + memoMap.map.delete(layer); + return close(entry.scope, exit); + }) + }; + return entry; +}; +const memoMapObserve = (entry, scope) => { + if (scope.state._tag === "Closed") return false; + entry.observers++; + scopeAddFinalizerUnsafe(scope, {}, entry.finalizer); + return true; +}; +const LayerProto = { + [TypeId]: { + _ROut: identity, + _E: identity, + _RIn: identity + }, + pipe() { + return pipeArguments(this, arguments); + } +}; +const fromBuildUnsafe = (build) => { + const self = Object.create(LayerProto); + self.build = build; + return self; +}; +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer. +* +* **Details** +* +* The function receives a `MemoMap` for memoization and a `Scope` for resource management. +* A child scope is created, and if the build fails, the child scope is closed. +* +* **Example** (Constructing a layer from a build function) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuild(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuild = (build) => fromBuildUnsafe((memoMap, scope) => { + const layerScope = forkUnsafe(scope); + return onExit(build(memoMap, layerScope), (exit) => exit._tag === "Failure" ? close(layerScope, exit) : void_); +}); +/** +* Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to +* build the layer, with automatic memoization. +* +* **Details** +* +* This is similar to `fromBuild` but provides automatic memoization of the layer construction. +* The layer will be memoized based on the provided `MemoMap`. +* +* **Example** (Memoizing layer construction) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const databaseLayer = Layer.fromBuildMemo(() => +* Effect.sync(() => +* Context.make(Database, { +* query: (sql: string) => Effect.succeed("result") +* }) +* ) +* ) +* +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, databaseLayer)) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const fromBuildMemo = (build) => { + const self = fromBuild((memoMap, scope) => memoMap.getOrElseMemoize(self, scope, build)); + return self; +}; +var MemoMapImpl = class { + get [MemoMapTypeId]() { + return MemoMapTypeId; + } + parent; + constructor(parent) { + this.parent = parent; + } + map = /*#__PURE__*/ new Map(); + get(layer, scope) { + const local = this.map.get(layer); + if (local) { + memoMapObserve(local, scope); + return local.deferred.effect ?? _await(local.deferred); + } + return this.parent?.get(layer, scope); + } + getOrElseMemoize(layer, scope, build) { + return suspend(() => { + let deferred; + return onExitPrimitive(suspend(() => { + const existing = this.get(layer, scope); + if (existing) return existing; + const entry = makeMemoMapEntry(this, layer); + if (!memoMapObserve(entry, scope)) return build(this, scope); + deferred = entry.deferred; + this.map.set(layer, entry); + return build(this, entry.scope); + }), (exit) => { + if (deferred) doneUnsafe(deferred, exit); + }); + }); + } +}; +/** +* Constructs a `MemoMap` synchronously so it can be used to build additional layers. +* +* **Example** (Creating a memo map unsafely) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* // Create a memo map for manual layer building +* const program = Effect.gen(function*() { +* const memoMap = Layer.makeMemoMapUnsafe() +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* return Context.get(context, Database) +* }) +* +* const database = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(database.query("SELECT 1")) // => "result" +* ``` +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const makeMemoMapUnsafe = () => new MemoMapImpl(); +/** +* Constructs a child `MemoMap` synchronously, allowing it to reuse layers +* already memoized in the parent while isolating any new layer allocations to +* the child map. +* +* **When to use** +* +* Use to synchronously fork a memo map for manual layer building when child +* builds should see parent memoized layers without writing newly built layers +* back to the parent. +* +* @see {@link forkMemoMap} for allocating the child memo map inside `Effect` +* @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent +* +* @stability stable +* @category constructors +* @since 4.0.0 +*/ +const forkMemoMapUnsafe = (parent) => new MemoMapImpl(parent); +/** +* Context service for the current `MemoMap` used in layer construction. +* +* **When to use** +* +* Use when building custom layer operations that need to access the current +* memoization map from the fiber context. +* +* **Details** +* +* This service wraps a `MemoMap` as a `Context.Service`, making it available +* for dependency injection during layer construction. +* +* @see {@link MemoMap} the memoization map type wrapped by this service +* +* @stability stable +* @category services +* @since 3.13.0 +*/ +var CurrentMemoMap = class CurrentMemoMap extends (/*#__PURE__*/ Service()("effect/Layer/CurrentMemoMap")) { + static forkOrCreate(self) { + const current = getOrUndefined(self, CurrentMemoMap); + return current ? forkMemoMapUnsafe(current) : makeMemoMapUnsafe(); + } +}; +/** +* Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize +* the layer construction. +* +* **Example** (Building layers with an explicit memo map) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const logs: Array = [] +* +* // Build layers with explicit memoization control +* const program = Effect.gen(function*() { +* const memoMap = yield* Layer.makeMemoMap +* const scope = yield* Effect.scope +* +* // Build database layer with memoization +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) +* +* // Build logger layer with same memoization (reuses memo if same layer) +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* const loggerContext = yield* Layer.buildWithMemoMap( +* loggerLayer, +* memoMap, +* scope +* ) +* +* return { +* database: Context.get(dbContext, Database), +* logger: Context.get(loggerContext, Logger) +* } +* }) +* +* const services = Effect.runSync(Effect.scoped(program)) +* Effect.runSync(services.logger.log("ready")) +* logs // => ["ready"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithMemoMap = /*#__PURE__*/ dual(3, (self, memoMap, scope) => provideService(map(suspend(() => self.build(memoMap, scope)), add(CurrentMemoMap, memoMap)), CurrentMemoMap, memoMap)); +/** +* Builds a layer using an explicit scope. +* +* **When to use** +* +* Use to control the lifetime of layer resources with a scope supplied by the +* caller. +* +* **Details** +* +* Resources created by the layer are released when the supplied scope is +* closed, unless a resource extends its own scope. +* +* **Example** (Building a layer with an explicit scope) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer, Scope } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const logs: Array = [] +* +* // Build a layer with explicit scope control +* const program = Effect.gen(function*() { +* const scope = yield* Effect.scope +* +* const dbLayer = Layer.effect(Database, Effect.gen(function*() { +* logs.push("Initializing database...") +* yield* Scope.addFinalizer( +* scope, +* Effect.sync(() => logs.push("Database closed")) +* ) +* return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } +* })) +* +* // Build with specific scope - resources tied to this scope +* const context = yield* Layer.buildWithScope(dbLayer, scope) +* const database = Context.get(context, Database) +* +* return yield* database.query("SELECT * FROM users") +* // Database will be closed when scope is closed +* }) +* +* Effect.runSync(Effect.scoped(program)) // => "Result: SELECT * FROM users" +* logs // => ["Initializing database...", "Database closed"] +* ``` +* +* @stability stable +* @category destructors +* @since 2.0.0 +*/ +const buildWithScope = /*#__PURE__*/ dual(2, (self, scope) => withFiber((fiber) => buildWithMemoMap(self, CurrentMemoMap.forkOrCreate(fiber.context), scope))); +/** +* Constructs a layer from an effect that produces a single service. +* +* **When to use** +* +* Use when you need to construct a `Layer`-provided service with an `Effect`, +* dependencies, or scoped resource acquisition. +* +* **Details** +* +* This allows you to create a `Layer` from an `Effect` that produces a service. +* The `Effect` is executed in the scope of the layer, allowing for proper +* resource management. +* +* **Example** (Creating a layer from an effect) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* const layer = Layer.effect(Database, +* Effect.sync(() => ({ +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effectContext} for effectfully providing multiple services +* @see {@link effectDiscard} for running construction work without providing services +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effect = function() { + if (arguments.length === 1) return (effect) => effectImpl(arguments[0], effect); + return effectImpl(arguments[0], arguments[1]); +}; +const effectImpl = (service, effect) => effectContext(map(effect, (value) => make(service, value))); +/** +* Constructs a layer from an effect that produces all services in a `Context`. +* +* **When to use** +* +* Use when you need a `Layer` that effectfully constructs a `Context` with +* multiple services. +* +* **Details** +* +* This allows you to create a `Layer` from an effectful computation that +* returns multiple services. The `Effect` is executed in the scope of the +* layer. +* +* **Example** (Creating a layer from an effectful context) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service< +* Database, +* { readonly query: (sql: string) => Effect.Effect } +* >()("Database") {} +* +* const layer = Layer.effectContext( +* Effect.succeed(Context.make(Database, { +* query: (sql: string) => Effect.succeed(`Query: ${sql}`) +* })) +* ) +* const program = Database.use((database) => database.query("SELECT 1")) +* Effect.runSync(Effect.provide(program, layer)) // => "Query: SELECT 1" +* ``` +* +* @see {@link effect} for effectfully providing a single service +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const effectContext = (effect) => fromBuildMemo((_, scope) => provide$2(effect, scope)); +const mergeAllEffect = (layers, memoMap, scope) => { + const parentScope = forkUnsafe(scope, "parallel"); + return forEach(layers, (layer) => layer.build(memoMap, forkUnsafe(parentScope, "sequential")), { concurrency: layers.length }).pipe(map((context) => mergeAll$1(...context))); +}; +/** +* Combines all the provided layers concurrently, creating a new layer with +* merged input, error, and output types. +* +* **When to use** +* +* Use when you need to combine multiple independent layers. +* +* **Details** +* +* All layers are built concurrently, and their outputs are merged into a single layer. +* +* If multiple merged layers depend on the same layer value, that dependency is +* shared by default. Reuse a named layer value when you want services to share +* the same resource, such as one database pool. +* +* **Example** (Merging independent layers) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* class Database extends Context.Service Effect.Effect +* }>()("Database") {} +* +* class Logger extends Context.Service Effect.Effect +* }>()("Logger") {} +* +* const dbLayer = Layer.succeed(Database, { +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) +* }) +* const logs: Array = [] +* const loggerLayer = Layer.succeed(Logger, { +* log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => logs.push(msg))) +* }) +* +* const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) +* const program = Logger.use((logger) => logger.log("ready")) +* Effect.runSync(Effect.provide(program, mergedLayer)) +* logs // => ["ready"] +* ``` +* +* @see {@link merge} for merging one layer with another layer or array +* +* @stability stable +* @category zipping +* @since 2.0.0 +*/ +const mergeAll = (...layers) => fromBuildMemo((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/internal/layer.js +const provideLayer = (self, layer, options) => scopedWith((scope) => flatMap(options?.local ? buildWithMemoMap(layer, makeMemoMapUnsafe(), scope) : buildWithScope(layer, scope), (context) => provideContext(self, context))); +/** @internal */ +const provide$1 = /*#__PURE__*/ dual((args) => isEffect(args[0]), (self, source, options) => isContext(source) ? provideContext(self, source) : provideLayer(self, Array.isArray(source) ? mergeAll(...source) : source, options)); +// ../../../../../../../node_modules/.pnpm/effect@4.1.2/node_modules/effect/dist/Effect.js +/** +* Provides a way to write effectful code using generator functions, simplifying +* control flow and error handling. +* +* **When to use** +* +* Use when you want to write effectful code that looks and behaves like +* synchronous code, while still handling asynchronous tasks, errors, and complex +* control flow such as loops and conditions. +* +* Generator functions work similarly to `async/await` but keep errors, +* requirements, and interruption in the Effect type. You can `yield*` values +* from effects and return the final result at the end. +* +* **Example** (Sequencing effects with generators) +* +* ```ts import.meta.vitest +* import { Data, Effect } from "effect" +* +* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} +* +* const addServiceCharge = (amount: number) => amount + 1 +* +* const applyDiscount = ( +* total: number, +* discountRate: number +* ): Effect.Effect => +* discountRate === 0 +* ? Effect.fail(new DiscountRateError()) +* : Effect.succeed(total - (total * discountRate) / 100) +* +* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100)) +* +* const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) +* +* export const program = Effect.gen(function*() { +* const transactionAmount = yield* fetchTransactionAmount +* const discountRate = yield* fetchDiscountRate +* const discountedAmount = yield* applyDiscount( +* transactionAmount, +* discountRate +* ) +* const finalAmount = addServiceCharge(discountedAmount) +* return `Final amount to charge: ${finalAmount}` +* }) +* +* await Effect.runPromise(program) // => "Final amount to charge: 96" +* ``` +* +* @stability stable +* @category constructors +* @since 2.0.0 +*/ +const gen = gen$1; +/** +* Provides dependencies to an effect using layers or a context. A layer already +* built by an enclosing `provide` or runtime is reused. Sibling `provide` calls +* build their own copies. Use `options.local` to build a fresh layer subtree. +* +* **Example** (Providing dependencies with a layer) +* +* ```ts import.meta.vitest +* import { Context, Effect, Layer } from "effect" +* +* interface Database { +* readonly query: (sql: string) => Effect.Effect +* } +* +* const Database = Context.Service("Database") +* +* const DatabaseLayer = Layer.succeed(Database)({ +* query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result for: ${sql}`)) +* }) +* +* const program = Effect.gen(function*() { +* const db = yield* Database +* return yield* db.query("SELECT * FROM users") +* }) +* +* const provided = Effect.provide(program, DatabaseLayer) +* +* await Effect.runPromise(provided) // => "Result for: SELECT * FROM users" +* ``` +* +* @stability stable +* @category providing services +* @since 2.0.0 +*/ +const provide = provide$1; +/** +* Executes an effect and returns the result as a `Promise`. +* +* **When to use** +* +* Use when you need to execute an effect and work with the +* result using `Promise` syntax, typically for compatibility with other +* promise-based code. +* +* If the effect succeeds, the promise will resolve with the result. If the +* effect fails, the promise will reject with an error. +* +* **Example** (Running a successful effect as a Promise) +* +* ```ts import.meta.vitest +* import { Effect } from "effect" +* +* await Effect.runPromise(Effect.succeed(1)) // => 1 +* ``` +* +* **Example** (Running effects as promises) +* +* ```ts import.meta.vitest +* //Example: Handling a Failing Effect as a Rejected Promise +* import { Effect } from "effect" +* const output: Array = [] +* +* await Effect.runPromise(Effect.fail("my error")).catch(() => { +* void output.push("rejected") +* }) +* output // => ["rejected"] +* ``` +* +* @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. +* @stability stable +* @category running +* @since 2.0.0 +*/ +const runPromise = runPromise$1; +// main.js +const Store = Service("test/RealUnusedHostImport"); +const readHelper = () => "read"; +const StoreLayer = effect(Store, gen(function* () { + const readOne = () => readHelper(); + return Store.of({ readOne }); +})); +const program = gen(function* () { + return [(yield* Store).readOne(), typeof compileFunction]; +}); +assert.deepStrictEqual(await runPromise(provide(program, StoreLayer)), ["read", "function"]); + +``` diff --git a/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/main.js b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/main.js new file mode 100644 index 000000000000..8d222ff8dc56 --- /dev/null +++ b/crates/rolldown/tests/rolldown/tree_shaking/effect_service_real/unused_host_import/main.js @@ -0,0 +1,27 @@ +import assert from "node:assert" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import { compileFunction } from "node:vm" + +// Importing a Node module observes nothing: only calls do. The pass must still +// remove `writeOne`. +const Store = Context.Service("test/RealUnusedHostImport") + +const readHelper = () => "read" +const writeHelper = () => "write" + +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const readOne = () => readHelper() + const writeOne = () => writeHelper() + return Store.of({ readOne, writeOne }) + }) +) + +const program = Effect.gen(function* () { + return [(yield* Store).readOne(), typeof compileFunction] +}) + +assert.deepStrictEqual(await Effect.runPromise(Effect.provide(program, StoreLayer)), ["read", "function"]) diff --git a/crates/rolldown_binding/src/generated/binding_checks_options.rs b/crates/rolldown_binding/src/generated/binding_checks_options.rs index a65add0c59df..618effada92c 100644 --- a/crates/rolldown_binding/src/generated/binding_checks_options.rs +++ b/crates/rolldown_binding/src/generated/binding_checks_options.rs @@ -32,6 +32,7 @@ pub struct BindingChecksOptions { pub sourcemap_broken: Option, pub namespace_conflict: Option, pub shimmed_export: Option, + pub effect_service_shaking: Option, } impl From for rolldown_common::ChecksOptions { fn from(value: BindingChecksOptions) -> Self { @@ -63,6 +64,7 @@ impl From for rolldown_common::ChecksOptions { sourcemap_broken: value.sourcemap_broken, namespace_conflict: value.namespace_conflict, shimmed_export: value.shimmed_export, + effect_service_shaking: value.effect_service_shaking, } } } diff --git a/crates/rolldown_binding/src/options/binding_input_options/binding_experimental_options.rs b/crates/rolldown_binding/src/options/binding_input_options/binding_experimental_options.rs index e35ff672e5f3..d9c1614831bf 100644 --- a/crates/rolldown_binding/src/options/binding_input_options/binding_experimental_options.rs +++ b/crates/rolldown_binding/src/options/binding_input_options/binding_experimental_options.rs @@ -14,6 +14,7 @@ pub struct BindingExperimentalOptions { pub native_magic_string: Option, pub chunk_optimization: Option>, pub lazy_barrel: Option, + pub effect_service_shaking: Option, } impl TryFrom for rolldown_common::ExperimentalOptions { @@ -38,6 +39,7 @@ impl TryFrom for rolldown_common::ExperimentalOption Either::B(v) => rolldown_common::ChunkOptimizationOption::Options(v.into()), }), lazy_barrel: value.lazy_barrel, + effect_service_shaking: value.effect_service_shaking, }) } } diff --git a/crates/rolldown_common/src/generated/checks_options.rs b/crates/rolldown_common/src/generated/checks_options.rs index 9c8a4adbef09..a031f1ba93b1 100644 --- a/crates/rolldown_common/src/generated/checks_options.rs +++ b/crates/rolldown_common/src/generated/checks_options.rs @@ -40,6 +40,7 @@ pub struct ChecksOptions { pub sourcemap_broken: Option, pub namespace_conflict: Option, pub shimmed_export: Option, + pub effect_service_shaking: Option, } impl From for rolldown_error::EventKindSwitcher { fn from(value: ChecksOptions) -> Self { @@ -140,6 +141,10 @@ impl From for rolldown_error::EventKindSwitcher { ); flag .set(rolldown_error::EventKindSwitcher::ShimmedExport, value.shimmed_export.unwrap_or(true)); + flag.set( + rolldown_error::EventKindSwitcher::EffectServiceShaking, + value.effect_service_shaking.unwrap_or(true), + ); flag } } diff --git a/crates/rolldown_common/src/inner_bundler_options/types/experimental_options.rs b/crates/rolldown_common/src/inner_bundler_options/types/experimental_options.rs index aea2b3217721..0e39063ba0eb 100644 --- a/crates/rolldown_common/src/inner_bundler_options/types/experimental_options.rs +++ b/crates/rolldown_common/src/inner_bundler_options/types/experimental_options.rs @@ -80,6 +80,8 @@ pub struct ExperimentalOptions { pub native_magic_string: Option, pub chunk_optimization: Option, pub lazy_barrel: Option, + /// Remove methods of Effect services that no consumer reads (experimental, off by default). + pub effect_service_shaking: Option, } impl ExperimentalOptions { @@ -100,6 +102,10 @@ impl ExperimentalOptions { self.attach_debug_info.is_some_and(|info| info.is_full()) } + pub fn is_effect_service_shaking_enabled(&self) -> bool { + self.effect_service_shaking.unwrap_or(false) + } + pub fn is_native_magic_string_enabled(&self) -> bool { self.native_magic_string.unwrap_or(false) } diff --git a/crates/rolldown_error/src/build_diagnostic/constructors.rs b/crates/rolldown_error/src/build_diagnostic/constructors.rs index 9a8a78e7c1e7..172a1b3954d6 100644 --- a/crates/rolldown_error/src/build_diagnostic/constructors.rs +++ b/crates/rolldown_error/src/build_diagnostic/constructors.rs @@ -509,6 +509,20 @@ impl BuildDiagnostic { }) } + pub fn effect_service_shaking( + module_id: Option, + tag: &'static str, + reason: String, + position: Option<(usize, usize)>, + ) -> Self { + Self::new_inner(super::events::effect_service_shaking::EffectServiceShaking { + module_id, + tag, + reason, + position, + }) + } + pub fn large_barrel_modules(module_id: String, reexport_count: usize) -> Self { Self::new_inner(super::events::large_barrel_modules::LargeBarrelModules { module_id, diff --git a/crates/rolldown_error/src/build_diagnostic/events/effect_service_shaking.rs b/crates/rolldown_error/src/build_diagnostic/events/effect_service_shaking.rs new file mode 100644 index 000000000000..1358f5122ed6 --- /dev/null +++ b/crates/rolldown_error/src/build_diagnostic/events/effect_service_shaking.rs @@ -0,0 +1,34 @@ +use super::BuildEvent; +use crate::{types::diagnostic_options::DiagnosticOptions, types::event_kind::EventKind}; + +/// A reason that turned `experimental.effectServiceShaking` off for the whole build, so +/// no service method was removed. Reported once per site. +#[derive(Debug)] +pub struct EffectServiceShaking { + pub module_id: Option, + pub tag: &'static str, + pub reason: String, + /// 1-based line and column of the site. + pub position: Option<(usize, usize)>, +} + +impl BuildEvent for EffectServiceShaking { + fn kind(&self) -> EventKind { + EventKind::EffectServiceShaking + } + + fn message(&self, opts: &DiagnosticOptions) -> String { + let site = match (&self.module_id, self.position) { + (Some(id), Some((line, column))) => { + format!(" at {line}:{column} in {}", opts.stabilize_path(id)) + } + (Some(id), None) => format!(" in {}", opts.stabilize_path(id)), + _ => String::new(), + }; + format!("[{}] {}{site}", self.tag, self.reason) + } + + fn id(&self) -> Option { + self.module_id.clone() + } +} diff --git a/crates/rolldown_error/src/build_diagnostic/events/mod.rs b/crates/rolldown_error/src/build_diagnostic/events/mod.rs index 2091179ae0b6..8c88c6905eac 100644 --- a/crates/rolldown_error/src/build_diagnostic/events/mod.rs +++ b/crates/rolldown_error/src/build_diagnostic/events/mod.rs @@ -22,6 +22,7 @@ pub mod commonjs_variable_in_esm; pub mod configuration_field_conflict; pub mod could_not_clean_directory; pub mod duplicate_shebang; +pub mod effect_service_shaking; pub mod empty_import_meta; pub mod eval; pub mod external_entry; diff --git a/crates/rolldown_error/src/generated/event_kind_switcher.rs b/crates/rolldown_error/src/generated/event_kind_switcher.rs index 95b537466fda..cf3eaaaaf5ef 100644 --- a/crates/rolldown_error/src/generated/event_kind_switcher.rs +++ b/crates/rolldown_error/src/generated/event_kind_switcher.rs @@ -57,5 +57,6 @@ bitflags! { const SourcemapBroken = 1 << 49; const NamespaceConflict = 1 << 50; const ShimmedExport = 1 << 51; + const EffectServiceShaking = 1 << 52; } } diff --git a/crates/rolldown_error/src/types/event_kind.rs b/crates/rolldown_error/src/types/event_kind.rs index ccad424b7e93..48deaf4c5711 100644 --- a/crates/rolldown_error/src/types/event_kind.rs +++ b/crates/rolldown_error/src/types/event_kind.rs @@ -139,6 +139,9 @@ pub enum EventKind { NamespaceConflict = 50, /// Whether to emit warnings when a missing export is replaced with an undefined binding. ShimmedExport = 51, + /// Whether to emit warnings explaining why `experimental.effectServiceShaking` kept the + /// methods of Effect services. + EffectServiceShaking = 52, } impl Display for EventKind { @@ -148,6 +151,7 @@ impl Display for EventKind { EventKind::AmbiguousExternalNamespaceError => write!(f, "AMBIGUOUS_EXTERNAL_NAMESPACES"), EventKind::NamespaceConflict => write!(f, "NAMESPACE_CONFLICT"), EventKind::ShimmedExport => write!(f, "SHIMMED_EXPORT"), + EventKind::EffectServiceShaking => write!(f, "EFFECT_SERVICE_SHAKING"), EventKind::CircularDependency => write!(f, "CIRCULAR_DEPENDENCY"), EventKind::CircularReexportError => write!(f, "CIRCULAR_REEXPORT"), EventKind::Eval => write!(f, "EVAL"), diff --git a/crates/rolldown_testing/_config.schema.json b/crates/rolldown_testing/_config.schema.json index 7876fe6bd71f..bb9af2dae7b9 100644 --- a/crates/rolldown_testing/_config.schema.json +++ b/crates/rolldown_testing/_config.schema.json @@ -1067,6 +1067,13 @@ "boolean", "null" ] + }, + "effectServiceShaking": { + "description": "Remove methods of Effect services that no consumer reads (experimental, off by default).", + "type": [ + "boolean", + "null" + ] } }, "additionalProperties": false @@ -1602,6 +1609,12 @@ "boolean", "null" ] + }, + "effectServiceShaking": { + "type": [ + "boolean", + "null" + ] } }, "additionalProperties": false diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index fdbc54a7ec99..4f9ed64f2da6 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -45,6 +45,7 @@ const sidebarForGuide: DefaultTheme.SidebarItem[] = [ { text: 'Dead Code Elimination', link: '/in-depth/dead-code-elimination.md' }, { text: 'Lazy Barrel Optimization', link: '/in-depth/lazy-barrel-optimization.md' }, { text: 'Native MagicString', link: '/in-depth/native-magic-string.md' }, + { text: 'Effect Service Shaking', link: '/in-depth/effect-service-shaking.md' }, ], }, { diff --git a/docs/in-depth/effect-service-shaking.md b/docs/in-depth/effect-service-shaking.md new file mode 100644 index 000000000000..ac6730ea3b9f --- /dev/null +++ b/docs/in-depth/effect-service-shaking.md @@ -0,0 +1,140 @@ +# Effect Service Shaking (experimental) + +An [Effect](https://effect.website) service is an object of methods behind a key. Rolldown keeps a whole object literal when any part of it is used, so a program that reads one method of a service still bundles every other method and every helper those methods reference. + +`experimental.effectServiceShaking` removes the methods nothing in the bundle can read. It is off by default and limited to a small set of Effect patterns. Anything else keeps every method, or turns the pass off for the whole build. + +```js +export default { + input: './main.js', + platform: 'node', + experimental: { + effectServiceShaking: true, + }, +}; +``` + +## What it handles + +Service keys are module-level declarations with a literal key string, as a `const` or a class whose body never mentions `this` or `super`: + +```js +const Store = Context.Service('app/Store'); +class Client extends Context.Service()('app/Client') {} +``` + +A class key's body may declare only static members with constant names, and none of them may redeclare what the key inherits from `Context.Service`: `of`, `key`, `use`, `useSync`, `context`, `pipe`, `toJSON`, `toString`, `name`, `length`, `prototype`, `caller`, `arguments`, `constructor`, the other `Object.prototype` members, or a `~` id. Any other class extending `Context.Service` turns the pass off. A class key's own static members (`OpenAiConfig.getOrUndefined`) may be read; other uses of the key follow the rules below. + +Consumers read methods from `yield* Key` inside `Effect.gen` or `Effect.fn`: + +```js +const program = Effect.gen(function* () { + const store = yield* Store; + return store.readOne(); +}); +``` + +Providers are `Layer.succeed(Key, { ... })`, or `Layer.effect(Key, effect)` where the effect is built from `Effect.gen`, `Effect.sync`, `Effect.succeed` and `Effect.acquireRelease`, and returns `Key.of({ ... })` or an object literal. A callback written as a named function expression is followed only when nothing references its name: through that name it can hand itself out and build another object from the same literal, so `Effect.sync(function inner() { exposed = inner; return { ... } })` keeps every method. Methods may be inline functions or constructor-local `const` functions: + +```js +const StoreLayer = Layer.effect( + Store, + Effect.gen(function* () { + const dependency = yield* Dependency; + const readOne = () => dependency.read(); + const writeOne = () => dependency.write(); + return Store.of({ readOne, writeOne }); + }), +); +``` + +With only `readOne` read anywhere, the pass removes `writeOne` from the provider. Because `writeOne` was the only reader of `dependency.write`, it also removes `write` from the `Dependency` provider. Rolldown's tree shaking then drops the helpers that only those methods used. + +Outside the effect package, a provider may also be built through functions, as generated clients are: + +```js +// Generated.js +export const make = (http) => ({ listModels: () => ..., retrieveModel: () => ... }); + +// Client.js +import * as Generated from './Generated.js'; +class Client extends Context.Service()('app/Client') {} +const make = Effect.fnUntraced(function* (options) { + const http = yield* HttpClient.HttpClient; + return Generated.make(http); +}, Effect.updateService(Headers.CurrentRedactedNames, append)); +export const layer = (options) => Layer.effect(Client, make(options)); + +// main.js +const ClientLayer = layer({ apiUrl }).pipe(Layer.provide(HttpLayer)); +``` + +The pass follows `Layer.effect(Key, make(args))` into a module-level `const` of the same module built by `Effect.fn` or `Effect.fnUntraced` from a generator function. Like a callback, that generator is not followed when it is a named function expression whose name is referenced. It follows `return value` and `return yield* effect` there, and then a call to a module-level function, in any module, that returns only object literals. That function must be a function declaration, an arrow or an anonymous function expression; a named function expression is not followed, because its own name can hand it out where the pass does not look. Those literals are provider objects only when every reference to the constructor and to the builder function is a call the pass followed into a provider; any other caller would get the same pruned object. The constructor's extra arguments must be `Effect.updateService`, `Effect.provideService`, `Effect.withSpan` or `Effect.annotateLogs` calls, which only change its context or tracing. A Layer returned from a module-level function is followed through each call of that function, and `layer.pipe(Layer.provide(a), ...)` with curried `Layer.provide`, `Layer.provideMerge` or `Layer.merge` is followed like the plain call. + +## What it never removes + +Demand is computed over code that can still run. Reads inside a removed method don't count. Anything that runs while a provider is constructed always counts. The pass deletes only object properties and unused constructor-local `const` functions. So service acquisition (`yield* Dep`), `acquireRelease` and its release, and construction-time calls keep running, in the same order. A property whose value is a binding is only removed when reading it cannot throw: the binding is a function declaration, a `var` or a parameter, or a `const`, `let`, class or catch binding declared earlier with no hoisted function declaration in between and not in a different case of the same `switch`. The read must also not run while the binding is still being initialised: inside the binding's own declaration (including an immediately invoked function or a class heritage there), inside the parameter list that declares it, inside the catch parameter pattern that declares it, or in the right-hand side of a `for…of` or `for…in` loop whose head declares it. An imported binding is always kept, because a module cycle can leave it uninitialised. This includes an import that resolves back to its own module, for example through a barrel that re-exports it. + +## When it keeps everything + +A service keeps every method when: +- its key is used in any way not listed above, such as `Key.use` or `Effect.map(Key, ...)`; +- the service value is passed anywhere, read with a computed key, or read through an inherited `Object.prototype` member; +- a kept provider method may read `this`, the object has getters, spreads or an explicit `__proto__`, or a release callback takes anything other than a single plain parameter. A method that may read `this` but is removed cannot run, so it keeps nothing; +- it is looked up other than by `yield*` with the key itself: `Context.get(context, Key)`, `Effect.updateService(Key, f)`, `Effect.provideService(Key, value)` and the other lookups listed below; +- its Layer may leave the bundle or be used in an unrecognised way. + +Everything else in Effect is allowed and ignored: forks, joins, run options, `Effect.map`, `Effect.all`, loggers, Schema, Stream, retries and timeouts. Holding a Fiber or a Context is fine; the contract below rules out reflecting on them. + +The pass is turned off for the whole build when user code: +- exports anything from the entry module, or imports an external module other than a Node builtin; +- loads code outside the module graph: `eval`, `Function`, `require`, a `.constructor` read, dynamic `import()`, `process.getBuiltinModule`, `module.createRequire`, or any use other than `typeof` of a binding imported from `vm`, `module`, `inspector` or `repl`, including through re-exports. A member name counts when the compiler can work it out: a string literal, a template literal, or `+` over them and over `const` bindings holding one, such as `fn["con" + "structor"]`. The same applies to the key argument of `Reflect.get` on the global `Reflect`, bare or through the global object (`globalThis.Reflect`), such as `Reflect.get(fn, "constructor")`, and of any method named `getOwnPropertyDescriptor`. That method is matched on any receiver as a conservative fallback, since aliases of `Object` are not tracked, so a user method with the same name is treated the same way. Calling one of them with a spread before the key, using them other than by calling them, or using the global `Reflect` other than through a member read or `typeof` (for example `const { get } = globalThis.Reflect`) also turns the pass off. A name built at run time is not checked (see A2); +- uses a host value that leads to code loaders (`process`, `globalThis`, `global`, `self`, `window`, `module`, or a namespace or default import of `node:process`) other than through constant member names, calls and `typeof`: for example `process[name]` or `const p = process`; +- looks a service up other than by `yield*` by something other than a declared key: `Context.get`, `getUnsafe`, `getOption`, `getOrElse`, `getOrUndefined`, `pick`, `omit`, `Effect.service`, `serviceOption`, `updateService`, `updateServiceScoped`, and `Layer`, `Stream` and `Channel.updateService`, with a key argument such as `{ key: "app/Store" }` or `cond ? A : B`; +- calls `Context.getOrUndefinedUnsafe` or `Context.makeUnsafe`, which work on key strings; +- uses `Context.Service` other than to declare a module-level key with a literal string, or writes to a key's members; +- modifies a builtin prototype or uses one as a value (`Map.prototype.get = ...`). + +## Contract + +The POC targets closed Effect applications. It relies on these assumptions, approved for the POC; programs that break them can be miscompiled instead of keeping methods: + +- **A1.** User code does not read, enumerate, serialise, format or mutate Effect runtime objects (Contexts, Fibers, Exits, Layers, Effect descriptions and their prototypes), and does not modify builtin prototypes. Services are reached only through keyed lookups. +- **A2.** The entry module exports nothing but primitive constants, and external imports are host builtins. Operations that load code (`eval`, `Function`, `require`, `vm`, `module.createRequire`) turn the pass off when the compiler can name them, including through the reflective reads `Reflect.get` and `getOwnPropertyDescriptor` with a constant key. User code does not reach a code loader through a member name built at run time, such as `(() => 0)[["con", "structor"].join("")]`. This is assumed, not checked: the pass does not detect it, and a program that does it can have methods removed and then fail at run time. Excluding it keeps ordinary computed reads on values other than services and host values, such as `settings[key]` or `fibers[i]`, from turning the pass off. +- **A3.** Effect's own modules read properties of user service values only through keyed lookups, and enumerate Context entries only under their own key prefixes. User keys don't use those prefixes. +- **A4.** Services are provided and read through the same bundled copy of `effect`. + +Some breaches are cheap to detect and turn the pass off rather than relying on A1: the string-keyed Context APIs (`Context.getOrUndefinedUnsafe`, `Context.makeUnsafe`), keyed lookups other than `yield*` by an untracked key, `Context.Service` used other than to declare a key, and writes to builtin prototypes. Every other Effect API is allowed. A consumer or provider shape the pass doesn't model keeps every method of the key involved. + +## Inspecting the result + +Every reason that turns the pass off is reported once per site as an `EFFECT_SERVICE_SHAKING` warning, with `at :` and the module. `checks.effectServiceShaking: false` silences them. + +Set `ROLLDOWN_EFFECT_SERVICE_SHAKING_REPORT=1` to print, for each build: +- why the pass was turned off, if it was; +- which keys kept every method, and why; +- the demand per key; +- every removed property and local. + +## Results + +The `tree_shaking/effect_service_real` fixtures run against the published `effect` package: + +| fixture | removed | preserved | +| --- | --- | --- | +| `lifecycle` | `writeOne`, the dependency's `write` and the audit service's `record`, plus their unique helpers | acquisition, construction-time calls and release, in order | +| `cross_module` | `writeOne` and its helper from another module | the live helper | +| `run_options` | `writeOne` and its helper, with `RunOptions.onFiberStart` | the program result | +| `retained_fiber` | `writeOne` and its helper, with a forked Fiber kept after it ends | the program result | + +`reflection_clean_data`, `provenance_json_clean`, `clean_builtin_callback`, `unused_host_import`, `provenance_success_channel` and `provenance_numeric_index` enumerate, serialise and transform user data, pass Effects through `Effect.map` and `Effect.all`, or import a Node module without calling it, and must still remove `writeOne`. `forged_key`, `builtin_prototype_write`, `node_prefixed_vm` and `host_module_loader` reach a service through a lookup by an untracked key, a patched builtin or code outside the bundle, and check that every method stays. The stub fixtures in `tree_shaking/effect_service` cover key identity, service escapes and writes, unsupported consumer shapes, provider shapes, lifecycle and the A2 boundary. + +`tree_shaking/effect_generated_client/openai` provides the generated client of `@effect/ai-openai` 4.1.2 through its service and calls only `retrieveModel` against a mock HTTP client. The pass keeps `retrieveModel` and its response schema and removes the other 378 methods, `httpClient` and the schemas only they used: the bundle goes from 2,068,645 to 532,916 bytes. It is not snapshotted and runs separately (`-- effect_generated_client`), because bundling it takes a few seconds. + +Once the `effect-verify` profile is built, `cargo test --profile effect-verify -p rolldown --test integration -- effect_service` runs every fixture in about 4 seconds. CI fails the step if it takes longer than 10 seconds. + +The analysis costs about 1.1–1.2x of an unoptimized build on Effect programs of 0.4–1.6 MB. + +## Limitations + +This is a proof of concept for the generator/constructor base case and generated clients. The `NodeFileSystem` provider builds its object by spreading a parameter, keyed access other than `yield*` keeps the key's methods (or turns the pass off for an untracked key), combinator consumers keep their key, constructors with other pipeables are not followed, and library builds with exports are not optimized. Programs that break the contract can be miscompiled instead of keeping methods. diff --git a/package.json b/package.json index 3ea253d7ef43..fa43711b52f8 100644 --- a/package.json +++ b/package.json @@ -18,10 +18,13 @@ "docs:preview": "pnpm --filter rolldown-docs run preview" }, "devDependencies": { + "@distilled.cloud/stripe": "1.0.0-rc.18", + "@effect/ai-openai": "4.1.2", "@oxc-node/core": "catalog:", "@oxc-project/runtime": "catalog:", "@types/node": "catalog:", "cjs-module-lexer": "^2.3.0", + "effect": "4.1.2", "knip": "^6.39.0", "playwright-chromium": "^1.63.0", "publint": "^0.3.21", diff --git a/packages/rolldown/src/binding.d.cts b/packages/rolldown/src/binding.d.cts index 1c1491288f01..43dfee6869bc 100644 --- a/packages/rolldown/src/binding.d.cts +++ b/packages/rolldown/src/binding.d.cts @@ -2024,6 +2024,7 @@ export interface BindingChecksOptions { sourcemapBroken?: boolean namespaceConflict?: boolean shimmedExport?: boolean + effectServiceShaking?: boolean } export interface BindingChunkImportMap { @@ -2316,6 +2317,7 @@ export interface BindingExperimentalOptions { nativeMagicString?: boolean chunkOptimization?: boolean | BindingChunkOptimizationOptions lazyBarrel?: boolean + effectServiceShaking?: boolean } export interface BindingFilterToken { diff --git a/packages/rolldown/src/options/generated/checks-options.ts b/packages/rolldown/src/options/generated/checks-options.ts index e3a6b6d42eef..69d001790af0 100644 --- a/packages/rolldown/src/options/generated/checks-options.ts +++ b/packages/rolldown/src/options/generated/checks-options.ts @@ -213,4 +213,11 @@ export interface ChecksOptions { * @default true * */ shimmedExport?: boolean; + + /** + * Whether to emit warnings explaining why `experimental.effectServiceShaking` kept the + * methods of Effect services. + * @default true + * */ + effectServiceShaking?: boolean; } diff --git a/packages/rolldown/src/options/input-options.ts b/packages/rolldown/src/options/input-options.ts index 75a1c71987d1..17cc80b7e174 100644 --- a/packages/rolldown/src/options/input-options.ts +++ b/packages/rolldown/src/options/input-options.ts @@ -731,6 +731,15 @@ export interface InputOptions { * @default false */ lazyBarrel?: boolean; + /** + * Remove methods of Effect services that no consumer in the bundle reads. + * + * Experimental and limited to providers built with `Layer.effect` / `Layer.succeed` + * and consumers using `yield*`. Anything else keeps every method. + * + * @default false + */ + effectServiceShaking?: boolean; }; /** * Configure how the code is transformed. This process happens after the `transform` hook. diff --git a/packages/rolldown/src/utils/bindingify-input-options.ts b/packages/rolldown/src/utils/bindingify-input-options.ts index 0117fa38d9ab..7665f7085c7d 100644 --- a/packages/rolldown/src/utils/bindingify-input-options.ts +++ b/packages/rolldown/src/utils/bindingify-input-options.ts @@ -205,6 +205,7 @@ function bindingifyExperimental( nativeMagicString: experimental?.nativeMagicString, chunkOptimization: experimental?.chunkOptimization, lazyBarrel: experimental?.lazyBarrel, + effectServiceShaking: experimental?.effectServiceShaking, }; } diff --git a/packages/rolldown/src/utils/validator.ts b/packages/rolldown/src/utils/validator.ts index 59f639e4dc21..b0709dbbad81 100644 --- a/packages/rolldown/src/utils/validator.ts +++ b/packages/rolldown/src/utils/validator.ts @@ -453,6 +453,12 @@ const ChecksOptionsSchema = v.strictObject({ 'Whether to emit warnings when a missing export is replaced with an undefined binding', ), ), + effectServiceShaking: v.pipe( + v.optional(v.boolean()), + v.description( + 'Whether to emit warnings explaining why `experimental.effectServiceShaking` kept the', + ), + ), }); isTypeTrue>(); @@ -707,6 +713,7 @@ const InputOptionsSchema = v.strictObject({ ]), ), lazyBarrel: v.optional(v.boolean()), + effectServiceShaking: v.optional(v.boolean()), }), ), transform: v.optional(TransformOptionsSchema), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 83fd83da4f5e..4fc79e7f2f53 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -431,6 +431,12 @@ importers: .: devDependencies: + '@distilled.cloud/stripe': + specifier: 1.0.0-rc.18 + version: 1.0.0-rc.18(effect@4.1.2) + '@effect/ai-openai': + specifier: 4.1.2 + version: 4.1.2(effect@4.1.2) '@oxc-node/core': specifier: 'catalog:' version: 0.1.7 @@ -443,6 +449,9 @@ importers: cjs-module-lexer: specifier: ^2.3.0 version: 2.3.0 + effect: + specifier: 4.1.2 + version: 4.1.2 knip: specifier: ^6.39.0 version: 6.42.1 @@ -2091,6 +2100,16 @@ packages: resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} + '@distilled.cloud/core@1.0.0-rc.18': + resolution: {integrity: sha512-Iui60+sNl1CwUu7NKGLuFf3VC4H9xYzfm0Fc8ZQvd87qwf1sDMB3EAWZrq/QFgrwzSY16z2mJ0PNHaBUnGet8A==} + peerDependencies: + effect: ^4.0.5 + + '@distilled.cloud/stripe@1.0.0-rc.18': + resolution: {integrity: sha512-BkD6bkYShbnSvy8uJbJ6iNVQZmaH+SFFym/UO0ycWdt8q4f9xGxIng65bqHDdOtO/RqMo4ZcuRih6cs+TCbB8Q==} + peerDependencies: + effect: ^4.0.5 + '@docsearch/css@4.7.0': resolution: {integrity: sha512-Sk5xkdRFeE7PeWjG9l4AfTwdvMfr9wHiwNNCpHXT4v4SNyNMKdHGvEILc31BgaVFGDDNbv5u/a73tofRiwbEZw==} @@ -2112,6 +2131,11 @@ packages: '@drizzle-team/brocli@0.10.2': resolution: {integrity: sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w==} + '@effect/ai-openai@4.1.2': + resolution: {integrity: sha512-u2RkBOj718eQQmZan3mJh0PJDLzhbZ4qFmMc/uSJhS0jmUoiaQI8SsCzENpNk0TRkt8lxEK4urohpeV5/xDWBQ==} + peerDependencies: + effect: ^4.1.2 + '@emnapi/core@1.11.2': resolution: {integrity: sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==} @@ -6739,6 +6763,9 @@ packages: ee-first@1.1.1: resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} + effect@4.1.2: + resolution: {integrity: sha512-d3Oah1WyKxFLFh19yWheS5IXIVaITzxZ71JkE1rkUozq/6EcJSU5nPk5bF2QrSygZ3SQoiNQB8TsxFriyMeMaQ==} + electron-to-chromium@1.5.372: resolution: {integrity: sha512-M3yhbAlilnwqC8D21t28UCDGHyitShTmmLRU/H+b74P6Ski16Nb9HONYEaVpMj/pwC7BEo5B95FpjODLCWbtfA==} @@ -10315,6 +10342,15 @@ snapshots: dependencies: '@jridgewell/trace-mapping': 0.3.9 + '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.2)': + dependencies: + effect: 4.1.2 + + '@distilled.cloud/stripe@1.0.0-rc.18(effect@4.1.2)': + dependencies: + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.2) + effect: 4.1.2 + '@docsearch/css@4.7.0': {} '@docsearch/css@5.1.0': {} @@ -10329,6 +10365,10 @@ snapshots: '@drizzle-team/brocli@0.10.2': {} + '@effect/ai-openai@4.1.2(effect@4.1.2)': + dependencies: + effect: 4.1.2 + '@emnapi/core@1.11.2': dependencies: '@emnapi/wasi-threads': 1.2.2 @@ -13884,6 +13924,8 @@ snapshots: ee-first@1.1.1: {} + effect@4.1.2: {} + electron-to-chromium@1.5.372: {} email-validator@2.0.4: {}